學習Python的過程中,遇到一個問題,在《Python學習手冊》(也就是《learning python》)中,元組、文件及其他章節里,關於處理二進制文件里,有這么一段代碼的處理:
>>>F=open('data.bin','wb')
>>>import struct
>>>data=struct.pack('i4sh',7,'spam',8)
>>>data
b'\x00\x00\x00\x07spam\x00\x08'
>>>F.write(data)\
>>>F.close()
實際上,無論是在python 2.x 或 3.x中,執行第三步data=struct,pack(...)時,輸出會報錯,報錯:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
data=struct.pack('>i4sh',7,'spam',8)
struct.error: argument for 's' must be a bytes object
查看幫助文檔,可以看到介紹:
ructstruct.
pack
(fmt, v1, v2, ...)
Return a bytes object containing the values v1, v2, � packed according to the format string fmt. The arguments must match the values required by the format exactly.
格式化字符串的值再Python中的類型是bytes類型,所以我們需要做處理。→在bytes類型前面加上一個b可以解決這個問題。
>>>data=struct,pack('>i4sh',7,b'spam',8)
b'\x00\x00\x00\x07spam\x00\x08'
到此問題解決!
struct.pack(fmt,v1,v2..),fmt是一種Linux命令,功能是編排文本文件。具體操作,此處不做過多記錄。
# 按照給定的格式(fmt),把數據封裝成字符串(實際上是類似於c結構體的字節流)
順便再做下‘>i4sh’的介紹,它在C數據結構和Python中的數據結構:
i-->int-->integer--->7
4s-->char-->string--->'spam'
h-->unsigned short-->integer-->8