我有一个很大的二进制文件。我如何写入(前置)到文件的开头?
例如:
file = 'binary_file'
string = 'bytes_string'
我希望得到包含以下内容的新文件:bytes_string_binary_file
。
构造 open("filename", ab)
仅附加。
我正在使用 Python 3.3.1。
最佳答案
无法添加到文件中。您必须完全重写该文件:
with open("oldfile", "rb") as old, open("newfile", "wb") as new:
new.write(string)
new.write(old.read())
如果您想避免将整个文件读入内存,只需按 block 读取即可:
with open("oldfile", "rb") as old, open("newfile", "wb") as new:
for chunk in iter(lambda: old.read(1024), b""):
new.write(chunk)
将 1024
替换为最适合您的系统的值。 (就是每次读取的字节数)。
关于python - 如何将数据添加到二进制文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16387639/