萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 二進制文件讀寫完全指南:struct 模組實戰

處理二進制資料(如整數、浮點數、C 結構體)時,Python 內建 struct 模組提供 pack/unpack 介面,能依指定格式將資料序列化為位元組串流或還原。本文詳解格式字串、檔案模式、常見陷阱與進階技巧。

核心概念:格式字串

格式字串由 字序前綴(可選)與 型別代碼 組成:

字序前綴含義
@原生字序、大小、對齊(預設)
=原生字序、標準大小、無對齊
<Little-endian,標準大小
>Big-endian,標準大小
!網路序(Big-endian),標準大小
型別代碼C 型別Python 型別標準大小
bsigned charint1
Bunsigned charint1
hshortint2
Hunsigned shortint2
iintint4
Iunsigned intint4
llongint4
qlong longint8
ffloatfloat4
ddoublefloat8
schar[]bytes依長度
pchar[] (Pascal string)bytes依長度

基本寫入與讀取

from struct import pack, unpack

# 寫入:一個 int(4B)、一個 double(8B)、一個 short(2B) = 共 14 bytes
with open('data.bin', 'wb') as f:
    f.write(pack('idh', 12345, 67.89, 15))

# 讀取:必須精確指定讀取位元組數
with open('data.bin', 'rb') as f:
    data = f.read(4 + 8 + 2)  # 14 bytes
    a, b, c = unpack('idh', data)
    print(a, b, c)  # 12345 67.89 15

關鍵點: 必須使用 'wb'/'rb' 二進制模式,否則 Windows 會轉換換行符導致資料損壞。

單一位元組操作

# 方法 1:ord() 轉整數
with open('data.bin', 'rb') as f:
    byte = f.read(1)
    val = ord(byte)
    print(hex(val))

# 方法 2:struct.unpack
import struct
with open('data.bin', 'rb') as f:
    byte = f.read(1)
    print(struct.unpack('b', byte))  # signed char
    print(struct.unpack('B', byte))  # unsigned char

十六進位字串與位元組互轉

import binascii

# hex string → bytes
hs = "5B7F888489FEDA"
hb = binascii.a2b_hex(hs)  # b'[\x7f\x88\x84\x89\xfe\xda'

# bytes → hex string
hb = b'[\x7f\x88\x84\x89\xfe\xda'
hs = binascii.b2a_hex(hb).decode()  # '5b7f888489feda'

進階:寫入原始十六進位碼

with open('test.bin', 'wb') as f:
    # 直接寫入位元組字面值
    f.write(b'\x5F\x9D\x3E')

# 追加模式
with open('test.bin', 'ab') as f:
    f.write(b'\x45\xF3')

常見錯誤與除錯

  • 大小不匹配:unpack 要求緩衝區大小完全等於格式字串對應大小,否則報 error: unpack requires a buffer of size X。
  • 字序不一致:跨平台交換資料請明確指定 '<' 或 '>'。
  • 簽名與無號混淆:'i' vs 'I',超出範圍會 struct.error。

總結

掌握 struct.pack/unpack 格式字串,即可高效處理二進制協定、檔案格式、硬體介面資料。建議搭配 ctypes 或 numpy.frombuffer 處理大量結構化二進制資料。

copyright © 萬盛學電腦網 all rights reserved