2015-06-21 44 views
0

我正在尝试编写一个脚本,它接受文件列表并在它们之间执行“逻辑或”操作。正如您在脚本中看到的那样,在第一阶段,我将创建一个空的append_buffer。然后我想要对列表中的所有文件进行逻辑OR操作。bin文件之间的逻辑“或”

我的问题是,当我读取文件时,我得到一个str而不是一个bytearray。所以当我试图执行or时失败了。我试图转换它没有任何成功。

 import struct 
     #import sys, ast 

     buffera = bytearray() 
     append_buffer = bytearray() 
     output_buffer = bytearray() 

     files_list=['E:\out.jpg','E:\loala2.jpg','E:\Koala.jpg','E:\loala2.jpg'] 
     print(files_list[1]) 


     ####################################################################################################################### 
     # create_dummy_bin_file_for_first_iteration , base on first file size 
     temp_file = open(files_list[1], "rb") 
     print (temp_file) 
     buffera = temp_file.read(temp_file.__sizeof__()) 
     temp_file.close() 

     for x in range(0, len(buffera)): 
      append_buffer.append(0x00) 
     ####################################################################################################################### 

     for i in range(1, len(files_list)): 
      print(files_list[i]) 
      file = open(files_list[i], "rb") 
      file_buffer = file.read(file.__sizeof__()) 
      file.close() 

      if (len(file_buffer) != len(append_buffer)): 
       print("Can't merge different size bin files ") 
       exit(1) 
      else: 

       for x in range(0, len(buffera)): 
        or_data=(file_buffer[x] | append_buffer[x]) 
        print("---") 
        print(type(file_buffer[x])) 
        print(file_buffer[x]) 

        print("---") 
        print(type(append_buffer[x])) 
        print(append_buffer[x]) 



     outputfile = open(files_list[0], "wb") 
     outputfile.write(output_buffer) 
     outputfile.close() 
+0

逐字节读取它们,执行或写入输出缓冲区。 – Rishav

回答

0

此代码示例使得在内存中完成的工作。

# Read data from the first file 
with open("file1.txt", "rt") as f: 
    d1 = f.read() 

# Read data from the second file 
with open("file2.txt", "rt") as f: 
    d2 = f.read() 

# Make sure that both sizes are equal 
assert len(d1) == len(d2) 

# Calculate OR-ed data 
d3 = "".join(chr(ord(d1[i]) | ord(d2[i])) for i in range(len(d1))) 

# Write the output data 
with open("file3.txt", "wt") as f: 
    f.write(d3) 

也可以逐字节地处理这些数据,以减少内存消耗。

+0

通过在'd3 = ...'中省略连接中的括号来保存一些内存,您可以使用生成器表达式而不是实际构建列表。 – engineerC

+0

@CaptainMurphy当然你是对的。我很遗憾这个疏忽。现在已经修复了。谢谢。 – dlask

1

您可以使用ordchr运营商做的每个字符转换为整数和背部。

利用这一点,你的代码将是:

or_data=chr(ord(file_buffer[x]) | ord(append_buffer[x])) 
+1

难道你不认为逐字节读取它们会使用更少的内存吗? – Rishav