我有两个二进制输入文件,firstfile
和secondfile
。 secondfile
是firstfile
+其他材料。我想在一个单独的文件中分离这些附加材料,newfile
。这是我到目前为止有:使用Python分割和编写二进制文件
import os
import struct
origbytes = os.path.getsize(firstfile)
fullbytes = os.path.getsize(secondfile)
numbytes = fullbytes-origbytes
with open(secondfile,'rb') as f:
first = f.read(origbytes)
rest = f.read()
当然,我的倾向是做(这似乎工作):
with open(newfile,'wb') as f:
f.write(rest)
我无法找到它,但以为我读了,让我在写入文件之前,应使用struct.pack
将其首先打包。下面给我一个错误:
with open(newfile,'wb') as f:
f.write(struct.pack('%%%ds' % numbytes,rest))
-----> error: bad char in struct format
但是这工作:
with open(newfile,'wb') as f:
f.write(struct.pack('c'*numbytes,*rest))
而且对于工作的人,这给了我正确的答案
with open(newfile,'rb') as f:
test = f.read()
len(test)==numbytes
-----> True
这是正确的方法写一个二进制文件?我只是想确保我正确地执行这部分来诊断文件的第二部分是否已损坏,因为我正在向newfile
提供的另一个读取器程序告诉我,或者我做错了。谢谢。
感谢您澄清'struct'的使用。 – hatmatrix