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)
483167 次浏览

使用 struct.pack将整数值转换为二进制字节,然后写入字节。

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

然而,我永远不会给一个二进制文件的 .txt扩展名。

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

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

要将 < 256的整数转换为二进制,请使用 chr函数。

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

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

from struct import pack
with open("foo.bin", "wb") as file:
file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))

下面是 shell 的一句俏皮话:

python -c $'from struct import pack\nwith open("foo.bin", "wb") as file: file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))'

对于 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]))

用泡菜,像这样: 进口泡菜

您的代码应该是这样的:

import pickle
mybytes = [120, 3, 255, 0, 100]
with open("bytesfile", "wb") as mypicklefile:
pickle.dump(mybytes, mypicklefile)

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

方便的函数将 int 数组写入文件,

def write_array(fname,ray):
'''
fname is a file pathname
ray is an array of int
'''
print("write:",fname)
EncodeInit()
buffer = [ encode(z) for z in ray ]
some = bytearray(buffer)
immutable = bytes(some)
with open(fname,"wb") as bfh:
wc = bfh.write(immutable)
print("wrote:",wrote)
return wc

如何调用函数,

write_array("data/filename",[1,2,3,4,5,6,7,8])

并将以下内容包装到一个可读的 encode/decode 类中:

Encode = {}
Decode = {}
def EncodeInit():
'''
Encode[] 0:62 as 0-9A-Za-z
Decode[] 0-9A-Za-z as 0:62
'''
for ix in range( 0,10): Encode[ix] = ix+ord('0')
for ix in range(10,36): Encode[ix] = (ix-10)+ord('A')
for ix in range(36,62): Encode[ix] = (ix-36)+ord('a')
for ix in range( 0,10): Decode[ix+ord('0')] = ix
for ix in range(10,36): Decode[(ix-10)+ord('A')] = ix
for ix in range(36,62): Decode[(ix-36)+ord('a')] = ix


def encode(x):
'''
Encode[] 0:62 as 0-9A-Za-z
Otherwise '.'
'''
if x in Encode: return Encode[x]
# else: error
return ord('.')


def decode(x):
'''
Decode[] 0-9A-Za-z as 0:62
Otherwise -1
'''
if x in Decode: return Decode[x]
# else: error
return -1