繁体   English   中英

Python如何写入二进制文件?

[英]Python how to write to a binary file?

我有一个字节列表作为整数,就像

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

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

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

但是我永远不会给二进制文件一个.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'))

从 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每次调用to_bytes创建一个长度为 1 的字符串,其字符以大端顺序排列(这对于长度为 1 的字符串来说是微不足道的),它表示整数值byte 您还可以将最后两行缩短为一行:

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

您可以使用以下使用 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])))'

将 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 = {}
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

使用泡菜,像这样:导入泡菜

您的代码如下所示:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM