python 读写二进制文件实例

本程序,首先写入一个矩阵到二进制文件中,然后读取二进制文件恢复到另外一个矩阵中。

#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)
上一篇:Duplicate id @+id/imageView, already defined earlier in this layout,android


下一篇:IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API