Python如何写入二进制文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18367007/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:34:26  来源:igfitidea点击:

Python how to write to a binary file?

python

提问by Aaron Hiniker

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)

采纳答案by abarnert

This is exactly what bytearrayis for:

这正是bytearray用于:

newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)

If you're using Python 3.x, you can use bytesinstead (and probably ought to, as it signals your intention better). But in Python 2.x, that won't work, because bytesis 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,则可以bytes改为使用(并且可能应该使用,因为它可以更好地表明您的意图)。但是在 Python 2.x 中,这不起作用,因为bytes它只是str. 像往常一样,用交互式解释器显示比用文本解释更容易,所以让我这样做。

Python 3.x:

Python 3.x:

>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'

Python 2.x:

Python 2.x:

>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'

回答by Mark Ransom

Use struct.packto convert the integer values into binary bytes, then write the bytes. E.g.

使用struct.pack的整数值转换成二进制字节,然后写入字节。例如

newFile.write(struct.pack('5B', *newFileBytes))

However I would never give a binary file a .txtextension.

但是我永远不会给二进制文件一个.txt扩展名。

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.

这种方法的好处是它也适用于其他类型,例如,如果任何值大于 255,您可以使用'5i'该格式来获取完整的 32 位整数。

回答by Perkins

To convert from integers < 256 to binary, use the chrfunction. So you're looking at doing the following.

要将小于 256 的整数转换为二进制,请使用该chr函数。因此,您正在考虑执行以下操作。

newFileBytes=[123,3,255,0,100]
newfile=open(path,'wb')
newfile.write((''.join(chr(i) for i in newFileBytes)).encode('charmap'))

回答by kenorb

You can use the following code example using Python 3 syntax:

您可以使用以下使用 Python 3 语法的代码示例:

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])))'

回答by CrepeGoat

As of Python 3.2+, you can also accomplish this using the to_bytesnative int method:

从 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'))

I.e., each single call to to_bytesin 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:

即,to_bytes在这种情况下,每次调用都会创建一个长度为 1 的字符串,其字符按大端顺序排列(这对于长度为 1 的字符串来说是微不足道的),它表示整数值byte。您还可以将最后两行缩短为一行:

newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))

回答by Raymond Mlambo

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

要读回数据,请使用 pickle.load 方法