Python中使用struct模組打包二進位制資料
阿新 • • 發佈:2019-02-14
執行環境:python3.4.3
demo.py:
f=open('s_data.bin','wb')
import struct
s=b'Allen'
data=struct.pack('>i5si',7,s,8)
print(data)
f.write(data)
f.close()
a,b,c=struct.unpack('>i5si',data)
print(a,b,c)
b=b.decode('utf-8')
print(b)
f2=open('b.txt','w')
f2.write(b)
f2.close()
控制檯輸出:
b'\x00\x00\x00\x07Allen\x 00\x00\x00\x08'
7 b'Allen' 8
Allen
[Finished in 0.3s]
s_data.bin:
0000 0007 416c 6c65 6e00 0000 08
b.txt:
Allen
Python3.0中必須使用bytes字串處理二進位制檔案,所以在字串前加b
識別符號即可,如:s=b'Allen'
pack函式第一個引數是格式化字串,如上面的>i5si
表示儲存格式為一個整數,一個5字元的字串,一個整數,>
表示按照高位在前(big-endian)的形式。
參考:
如果我們要講bytes字串轉換為unicode字串,需要b=b.decode('utf-8')
如果要解析一個二進位制檔案的話:
demo.py:
import struct
f=open('s_data.bin','rb')
data=f.read()
print(data)
a,b,c=struct.unpack('>i5si',data)
print(a,b,c)
控制檯輸出:
b'\x00\x00\x00\x07Allen\x00\x00\x00\x08'
7 b'Allen' 8
Python2和Python3中對於文字檔案和二進位制檔案處理方式不盡相同,所以還要依據開發環境選擇不同的處理方法,