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

#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)

 

相关文章:

  • 2021-12-27
  • 2022-03-12
  • 2021-11-11
  • 2021-10-06
  • 2021-12-01
  • 2021-08-19
  • 2021-06-26
猜你喜欢
  • 2021-09-30
  • 2021-09-16
  • 2022-12-23
  • 2022-01-16
  • 2022-12-23
  • 2022-12-23
  • 2022-01-06
相关资源
相似解决方案