【发布时间】: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