Python 如何将数据前置到二进制文件?
我有一个大的二进制文件。如何写入(前置)文件的开头 例: 我希望得到内容为:Python 如何将数据前置到二进制文件?,python,file,python-3.x,Python,File,Python 3.x,我有一个大的二进制文件。如何写入(前置)文件的开头 例: 我希望得到内容为:bytes\u string\u binary\u 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())
bytes\u string\u binary\u 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())
如果要避免将整个文件读入内存,只需按块读取:
with open("oldfile", "rb") as old, open("newfile", "wb") as new:
for chunk in iter(lambda: old.read(1024), b""):
new.write(chunk)
将
1024
替换为最适合您的系统的值。(这是每次读取的字节数)。非常感谢您的解决方案,但我的操作内存有限。。也许是另一种解决办法?还是不可能?@wikicms添加了一个只使用有限内存的解决方案,使用function.OMG,你在python中掌握的!谢谢@大卫,谢谢你编辑我的问题。
with open("oldfile", "rb") as old, open("newfile", "wb") as new:
for chunk in iter(lambda: old.read(1024), b""):
new.write(chunk)