使用結構爲二進制我有以下的字典,我想編寫一個文件二進制:轉換數據在python
data = {(7, 190, 0): {0: 0, 1: 101, 2: 7, 3: 0, 4: 0},
(7, 189, 0): {0: 10, 1: 132, 2: 17, 3: 20, 4: 40}}
我繼續使用這樣的結構模塊:
packed=[]
for ssd, add_val in data.iteritems():
# am trying to using 0xcafe as a marker to tell me where to grab the keys
pack_ssd = struct.pack('HBHB', 0xcafe, *ssd)
packed.append(pack_ssd)
for add, val in data[ssd].iteritems():
pack_add_val = struct.pack('HH', add, val)
packed.append(pack_add_val)
這個輸出是packed = ['xx \ xca \ x00 \ x00','\ x00 \ x00 \ x00','\ x00 \ x00 \ x00' x00 \ x00 \ x00','\ x04 \ x00 \ x00 \ x00','\ xfe \ xca \ x07 \ x00','x00' x00 \ x00 \ n00 \ x00','\ x01 \ x00 \ x84 \ x00','\ x02 \ x00 \ x11 \ x00','\ x03 \ x00 \ x14 \ x00','\ x04 \ x00 ']
這之後,我寫這篇文章的二進制文件:
ifile = open('test.bin', 'wb')
for pack in packed:
ifile.write(pack)
下面是二進制文件看起來像: 「\ XFE \ XCA \ X07 \ X00 \ XBE \ X00 \ X00 \ X00 \ X00 \ X00 \ X00 \ X01 \ x00e \ X00 \ X02 \ X00 \ X07 \ X00 \ X03 \ X00 \ X00 \ X00 \ X04 \ X00 \ X00 \ X00 \ XFE \ XCA \ X07 \ X00 \ XBD \ X00 \ X00 \ X00 \ x00 \ x00 \ x100 \ x00 \ x00 \ x02 \ x00 \ x11 \ x00 \ x03 \ x00 \ x14 \ x00 \ x04 \ x00(\ x00'
直到我試圖解開數據。現在我想讀取二進制文件的內容,並重新安排我的字典首先看起來很喜歡。這是我試圖解開它,但我總是得到一個錯誤:
unpack=[]
while True:
chunk = ifile.read(log_size)
if len(chunk) == log_size:
str = struct.unpack('HBHB', chunk)
unpack.append(str)
chunk = ifile.read(log1_size)
str= struct.unpack('HH', chunk)
unpack.append(str)
Traceback (most recent call last):
File "<interactive input>", line 7, in ?
error: unpack str size does not match format
我意識到我試圖解壓總是會遇到問題的方法,但我似乎無法找到拆包的好方法二進制文件的內容。任何幫助非常感謝..
除非這是家庭作業,http://stackoverflow.com/questions/8968884/python-serialization-why-pickle http://docs.python.org/2/library/pickle.html http:// docs。 python.org/2/library/marshal.html – Patashu 2013-05-07 03:44:28