繁体   English   中英

使用numpy读取二进制文件中的几个数组

[英]Reading several arrays in a binary file with numpy

我正在尝试读取一个二进制文件,该文件由几个由单个int分隔的浮点数矩阵组成。 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)

这对于第一个数组工作正常,但不会读取下一个矩阵。 知道我该怎么做吗?

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

谢谢

在单个矢量化语句中读取所有矩阵的最干净方法是使用struct数组:

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'])

有两种解决方案。

第一个:

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

在哪里是你想得到的数组。

第二个:

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”打开文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM