Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将数据前置到二进制文件?_Python_File_Python 3.x - Fatal编程技术网

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)