问题:Python如何写入二进制文件?
我有一个字节列表作为整数,这就像
[120, 3, 255, 0, 100]
如何将该列表作为二进制文件写入文件?
这行得通吗?
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
newFile.write(newFileBytes)
I have a list of bytes as integers, which is something like
[120, 3, 255, 0, 100]
How can I write this list to a file as binary?
Would this work?
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
newFile.write(newFileBytes)
回答 0
这正是bytearray
用于:
newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)
如果您使用的是Python 3.x,则可以bytes
改用(也许应该这样做,因为它可以更好地表明您的意图)。但是在Python 2.x中,这bytes
是行不通的,因为它只是的别名str
。像往常一样,使用交互式解释器进行显示比使用文本进行解释要容易,所以让我这样做。
Python 3.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'
Python 2.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'
This is exactly what bytearray
is for:
newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)
If you’re using Python 3.x, you can use bytes
instead (and probably ought to, as it signals your intention better). But in Python 2.x, that won’t work, because bytes
is just an alias for str
. As usual, showing with the interactive interpreter is easier than explaining with text, so let me just do that.
Python 3.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'
Python 2.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'
回答 1
使用struct.pack
的整数值转换成二进制字节,然后写入字节。例如
newFile.write(struct.pack('5B', *newFileBytes))
但是,我永远不会给二进制文件.txt
扩展名。
此方法的好处是它也适用于其他类型,例如,如果任何值大于255,都可以使用'5i'
该格式代替获取完整的32位整数。
Use struct.pack
to convert the integer values into binary bytes, then write the bytes. E.g.
newFile.write(struct.pack('5B', *newFileBytes))
However I would never give a binary file a .txt
extension.
The benefit of this method is that it works for other types as well, for example if any of the values were greater than 255 you could use '5i'
for the format instead to get full 32-bit integers.
回答 2
要将<256的整数转换为二进制,请使用chr
函数。因此,您正在考虑执行以下操作。
newFileBytes=[123,3,255,0,100]
newfile=open(path,'wb')
newfile.write((''.join(chr(i) for i in newFileBytes)).encode('charmap'))
To convert from integers < 256 to binary, use the chr
function. So you’re looking at doing the following.
newFileBytes=[123,3,255,0,100]
newfile=open(path,'wb')
newfile.write((''.join(chr(i) for i in newFileBytes)).encode('charmap'))
回答 3
从Python 3.2+开始,您还可以使用本to_bytes
机int方法完成此操作:
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
newFile.write(byte.to_bytes(1, byteorder='big'))
也就是说,to_bytes
在这种情况下,每次调用都会创建一个长度为1的字符串,其字符以大端顺序排列(对于长度为1的字符串而言,这是微不足道的),它表示整数值byte
。您还可以将最后两行缩短为一行:
newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))
As of Python 3.2+, you can also accomplish this using the to_bytes
native int method:
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
newFile.write(byte.to_bytes(1, byteorder='big'))
I.e., each single call to to_bytes
in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte
. You can also shorten the last two lines into a single one:
newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))
回答 4
您可以使用以下使用Python 3语法的代码示例:
from struct import pack
with open("foo.bin", "wb") as file:
file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))
这是外壳一线:
python -c $'from struct import pack\nwith open("foo.bin", "wb") as file: file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))'
You can use the following code example using Python 3 syntax:
from struct import pack
with open("foo.bin", "wb") as file:
file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))
Here is shell one-liner:
python -c $'from struct import pack\nwith open("foo.bin", "wb") as file: file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))'
回答 5
像这样使用泡菜:导入泡菜
您的代码如下所示:
import pickle
mybytes = [120, 3, 255, 0, 100]
with open("bytesfile", "wb") as mypicklefile:
pickle.dump(mybytes, mypicklefile)
要读回数据,请使用pickle.load方法
Use pickle, like this: import pickle
Your code would look like this:
import pickle
mybytes = [120, 3, 255, 0, 100]
with open("bytesfile", "wb") as mypicklefile:
pickle.dump(mybytes, mypicklefile)
To read the data back, use the pickle.load method