簡體   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