我有一个字节列表作为整数,这是类似的
[120, 3, 255, 0, 100]
Run Code Online (Sandbox Code Playgroud)
如何将此列表作为二进制文件写入文件?
这会有用吗?
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
newFile.write(newFileBytes)
Run Code Online (Sandbox Code Playgroud)
aba*_*ert 109
这正是bytearray
为了:
newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是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'
Run Code Online (Sandbox Code Playgroud)
Python 2.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'
Run Code Online (Sandbox Code Playgroud)
Mar*_*som 26
使用struct.pack
的整数值转换成二进制字节,然后写入字节.例如
newFile.write(struct.pack('5B', *newFileBytes))
Run Code Online (Sandbox Code Playgroud)
但是,我永远不会给二进制文件一个.txt
扩展名.
这种方法的好处是它也适用于其他类型,例如,如果任何值大于255,您可以使用'5i'
该格式来获得完整的32位整数.
要将整数<256转换为二进制,请使用该chr
函数.所以你正在考虑做以下事情.
newFileBytes=[123,3,255,0,100]
newfile=open(path,'wb')
newfile.write((''.join(chr(i) for i in newFileBytes)).encode('charmap'))
Run Code Online (Sandbox Code Playgroud)
您可以使用以下使用Python 3语法的代码示例:
from struct import pack
with open("foo.bin", "wb") as file:
file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))
Run Code Online (Sandbox Code Playgroud)
这是外壳一线:
python -c $'from struct import pack\nwith open("foo.bin", "wb") as file: file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))'
Run Code Online (Sandbox Code Playgroud)
从Python 3.2+开始,您还可以使用to_bytes
native 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'))
Run Code Online (Sandbox Code Playgroud)
也就是说,to_bytes
在这种情况下,每次调用都会创建一个长度为1的字符串,其字符以big-endian顺序排列(对于长度为1的字符串来说这是微不足道的),它表示整数值byte
.您还可以将最后两行缩短为一行:
newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))
Run Code Online (Sandbox Code Playgroud)