在python中创建二进制文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21910059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create binary file in python
提问by Subway
I have a very large binary file called file1.bin and I want to create a file, file2.bin, that holds only the first 32kb of file1.bin.
我有一个名为 file1.bin 的非常大的二进制文件,我想创建一个文件 file2.bin,它只包含 file1.bin 的前 32kb。
So I'm reading file1 as follows:
所以我正在阅读 file1 如下:
myArr = bytearray()
with open(r"C:\Users\User\file1.bin", "rb") as f:
byte = f.read(1)
for i in range(32,678):
myArr.extend(byte)
byte = f.read(1)
My question is: How do I proceed from here to create the file2 binary file out of myArr?
我的问题是:如何从这里开始从 myArr 创建 file2 二进制文件?
I tried
我试过
with open(r"C:\Users\User\file2.bin", "w") as f:
f.write(myArr)
but this results in:
但这导致:
f.write(myArr)
TypeError: must be string or pinned buffer, not bytearray
采纳答案by Joel Cornett
You need to open the file in binary write mode (wb).
您需要以二进制写入模式 ( wb)打开文件。
with open('file2.bin', 'wb') as f:
f.write(myArr)
Also, the way you are reading from the input file is pretty inefficient. f.read()allows you to read more than one byte at a time:
此外,您从输入文件中读取的方式非常低效。f.read()允许您一次读取多个字节:
with open('file1.bin', 'rb') as f:
myArr = bytearray(f.read(32678))
Will do exactly what you want.
会做你想做的。
回答by J. Katzwinkel
Open files with appropriate flags, then read from one in blocks of 1024 bytes and write to other, if less than 1024 bytes are remaining, copy byte-wise.
使用适当的标志打开文件,然后从一个 1024 字节的块中读取并写入另一个,如果剩余的少于 1024 个字节,则逐字节复制。
fin = open('file1.bin', 'rb')
fout = open('file2.bin', 'w+b')
while True:
b=fin.read(1024)
if b:
n = fout.write(b)
else:
while True:
b=fin.read(1)
if b:
n=fout.write(b)
else:
break
break

