使用Python分割和编写二进制文件
问题描述:
我有两个二进制输入文件,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
模块,该模块用于在二进制格式和Python对象之间进行转换。这里不需要转换。
Python 2.x中的字符串只是一个字节数组,可以在文件中读写。 (在Python 3中。,X,读函数返回一个bytes
对象,这是同样的事情,如果你打开该文件open(filename, 'rb')
)
所以,你可以只读取文件转换成字符串,然后再写一遍:
import os
origbytes = os.path.getsize(firstfile)
fullbytes = os.path.getsize(secondfile)
numbytes = fullbytes-origbytes
with open(secondfile,'rb') as f:
first = f.seek(origbytes)
rest = f.read()
with open(newfile,'wb') as f:
f.write(rest)
答
如果你知道secondfile是与firstfile +附加数据相同,为什么即使读取第二个文件的第一部分?
with open(secondfile,'rb') as f:
f.seek(origbytes)
rest = f.read()
至于写出来的东西,
with open(newfile,'wb') as f:
f.write(rest)
就好了。无论如何,与struct
的东西将只是一个没有操作。您可能会考虑的唯一的事情是rest
的大小。如果它可能很大,您可能需要读取和写入数据块。
答
- 你并不需要阅读
origbytes
,只需将文件指针到合适的位置:f.seek(numbytes)
- 你不需要
struct
包装,写rest
到newfile
。
感谢您澄清'struct'的使用。 – hatmatrix