使用Python分段和写入二进制文件

0 投票
4 回答
1805 浏览
提问于 2025-04-17 06:37

我有两个二进制输入文件,firstfilesecondfilesecondfile 是在 firstfile 的基础上加了一些额外的内容。我想把这些额外的内容单独放到一个新文件里,叫 newfile。这是我目前的做法:

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)

我找不到相关的信息,但我记得在StackOverflow上看到过,写入文件之前应该先用 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 的另一个程序告诉我可能有问题,或者是我做错了。谢谢。

4 个回答

1
  1. 你不需要去读取 origbytes,只要把文件指针移动到正确的位置就行:f.seek(numbytes)
  2. 你不需要使用 struct 来打包数据,直接把 rest 写入 newfile 就可以了。
3

如果你知道第二个文件的内容是第一个文件加上一些附加的数据,那为什么还要读取第二个文件的前半部分呢?

with open(secondfile,'rb') as f:
    f.seek(origbytes)
    rest = f.read()

至于写入数据,

with open(newfile,'wb') as f:
    f.write(rest)

这样做是完全可以的。使用struct的部分其实也没什么用。你唯一需要考虑的就是rest的大小。如果它可能很大,你可能需要分块读取和写入数据。

2

其实没有必要使用 struct 模块,因为这个模块是用来在二进制格式和Python对象之间转换的。而在这里,我们并不需要进行这样的转换。

在Python 2.x中,字符串其实就是一组字节,可以直接从文件中读取和写入。(在Python 3.x中,如果你用 open(filename, 'rb') 打开文件,读取的内容会返回一个 bytes 对象,其实和字节是一样的。)

所以你可以直接把文件内容读入一个字符串,然后再写回去:

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)

撰写回答