gpt4 book ai didi

Python如何写入二进制文件?

转载 作者:IT老高 更新时间:2023-10-28 21:08:04 25 4
gpt4 key购买 nike

我有一个整数字节列表,类似于

[120, 3, 255, 0, 100]

如何将此列表作为二进制文件写入文件?

这行得通吗?

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
newFile.write(newFileBytes)

最佳答案

这正是 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]'

关于Python如何写入二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18367007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com