我尝试使用Python从二进制文件中读取带有浮点数的二维数组。文件是用Fortran程序用big endian编写的(它是Weather Research and Forecast模型的中间文件)。我已经知道要读取的数组的维度大小(nx& ny)但作为Fortran和IDl程序员我完全迷失了,如何在Python中管理它。 (后来我想要可视化数组)。
struct.unpack
或numpy.fromfile
还是array module
?答案 0 :(得分:1)
每个子问题的简短答案:
array
模块没有办法指定字节顺序。
在struct
模块和Numpy之间,我认为Numpy更容易
使用,特别是对于类似Fortran的有序数组。numpy.fromfile
重塑必须发生
明确地说,但是numpy.memmap
提供了一种重塑的方法
更含蓄地。struct
module非常相似。在Numpy中>f
和>f4
指定单个
精度和>d
和>f8
双精度大端浮动
点。order
和reshape
(以及其他)的memmap
关键字参数。总而言之,代码可以是例如:
import numpy as np
filename = 'somethingsomething'
with open(filename, 'rb') as f:
nx, ny = ... # parse; advance file-pointer to data segment
data = np.fromfile(f, dtype='>f8', count=nx*ny)
array = np.reshape(data, [nx, ny], order='F')