【问题标题】:Reading several arrays in a binary file with numpy使用 numpy 读取二进制文件中的多个数组
【发布时间】:2016-08-30 10:30:06
【问题描述】:

我正在尝试读取由多个浮点数矩阵组成的二进制文件,该浮点数矩阵由一个整数分隔。 Matlab中实现这一点的代码如下:

fid1=fopen(fname1,'r');
for i=1:xx
    Rstart= fread(fid1,1,'int32');        #read blank at the begining
    ZZ1 = fread(fid1,[Nx Ny],'real*4');   #read z
    Rend  = fread(fid1,1,'int32');        #read blank at the end
end

如您所见,每个矩阵大小为 Nx x Ny。 Rstart 和 Rend 只是虚拟值。 ZZ1 是我感兴趣的矩阵。

我正在尝试在 python 中做同样的事情,执行以下操作:

Rstart = np.fromfile(fname1,dtype='int32',count=1)
ZZ1 = np.fromfile(fname1,dtype='float32',count=Ny1*Nx1).reshape(Ny1,Nx1)
Rend = np.fromfile(fname1,dtype='int32',count=1)

然后,我必须迭代以读取后续矩阵,但函数 np.fromfile 不会保留文件中的指针。

另一种选择:

with open(fname1,'r') as f:
   ZZ1=np.memmap(f, dtype='float32', mode='r', offset = 4,shape=(Ny1,Nx1))
   plt.pcolor(ZZ1)

这适用于第一个数组,但不会读取下一个矩阵。知道我该怎么做吗?

我搜索了类似的问题,但没有找到合适的答案。

谢谢

【问题讨论】:

  • numpy.fromfile 也接受文件对象作为第一个参数。
  • 完美。这正是我想要的。重要的是指出文件应该以二进制模式打开,例如 fid=open(fname,'rb') 。谢谢!

标签: python matlab numpy io binary


【解决方案1】:

在单个向量化语句中读取所有矩阵的最简洁方法是使用结构数组:

dtype = [('start', np.int32), ('ZZ', np.float32, (Ny1, Nx1)), ('end', np.int32)]
with open(fname1, 'rb') as fh:
    data = np.fromfile(fh, dtype)
print(data['ZZ'])

【讨论】:

  • 漂亮的答案!我不确定复合 dtype 是如何工作的。谢谢。
  • 我认为的缺点是它一次加载所有数组,我应该避免使用大文件。
  • 我认为您仍然可以向 fromfile 添加计数参数,不是吗?
【解决方案2】:

这个问题有两种解决方案。

第一个:

for i in range(x):
    ZZ1=np.memmap(fname1, dtype='float32', mode='r', offset = 4+8*i+(Nx1*Ny1)*4*i,shape=(Ny1,Nx1))

其中 i 是您要获取的数组。

第二个:

fid=open('fname','rb')
for i in range(x):
    Rstart = np.fromfile(fid,dtype='int32',count=1)
    ZZ1 = np.fromfile(fid,dtype='float32',count=Ny1*Nx1).reshape(Ny1,Nx1)
    Rend = np.fromfile(fid,dtype='int32',count=1)

正如 Morningsun 指出的,np.fromfile 可以接收文件对象作为参数并跟踪指针。请注意,您必须以二进制模式“rb”打开文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多