1 ''' 2 使用struct模塊寫入二進制文件 3 ''' 4 import struct 5 n=130000000 6 x=96.45 7 b=True 8 s='a1@中國' 9 sn=struct.pack('if?',n,x,b) #序列化,i表示整數,f表示實數,?表示邏輯值 10 f=open('sample_struct.dat','wb') 11 f.write(sn) 12 f.write(s.encode()) #字符串需要編碼為字節串再寫入文件 13 f.close() 14 15 ''' 16 使用struct模塊讀取二進制文件的內容 17 ''' 18 import struct 19 f=open('sample_struct.dat','rb') 20 sn=f.read(9) 21 tu=struct.unpack('if?',sn) #使用指定格式反序列化 22 print(tu) 23 print('n=',n,'x=',x,'b=',b) 24 s=f.read(9) 25 s=s.decode() #字符串解碼 26 print('s=',s) #字符串解碼 27 28 ''' 29 讀取字節的長度 30 ''' 31 import struct 32 st=struct.pack('if?',13000,56.0,True) 33 print(len(st)) 34 x='a1@中國' 35 print(len(x.encode()))
#輸出的結果
(130000000, 96.44999694824219, True)
n= 130000000 x= 96.45 b= True
s= a1@中國
9
9