python 讀寫二進制文件實例
阿新 • • 發佈:2018-07-17
port log sam com style div with ack www
本程序,首先寫入一個矩陣到二進制文件中,然後讀取二進制文件恢復到另外一個矩陣中。
#coding:utf--8 #https://www.cnblogs.com/cmnz/p/6986979.html #https://blog.csdn.net/uuihoo/article/details/79848726 import struct import numpy as np a = np.arange(3*4, dtype=np.int32).reshape((3,4)) print(a) with open(‘sample_struct.dat‘,‘wb‘) as f: for row in range(3):for col in range(4): sn=struct.pack(‘i‘,a[row][col]) #序列化,i表示整數,f表示實數,?表示邏輯值 f.write(sn) b = np.zeros((3,4), dtype=np.int32) with open(‘sample_struct.dat‘,‘rb‘) as f: for row in range(3): for col in range(4): sn=f.read(4) b[row][col],=struct.unpack(‘i‘,sn) #使用指定格式反序列化 print(b)
python 讀寫二進制文件實例