Python:使用 numpy 或 scipy 读取 Fortran 二进制文件
Python: Reading Fortran Binary file using numpy or scipy
我正在尝试读取一个 Fortran 文件,其中 headers 作为整数,然后将实际数据作为 32 位浮点数。使用 numpy 的 fromfile('mydatafile', dtype=np.float32)
它将整个文件读取为 float32,但我需要 headers 在 int32 中作为我的输出文件。使用 scipy 的 FortranFile,它读取 headers:
f = FortranFile('mydatafile', 'r')
headers = f.read_ints(dtype=np.int32)
但当我这样做时:
data = f.read_reals(dtype=np.float32)
它 returns 一个空数组。我知道它不应该为空,因为它使用 numpy 的 fromfile 读取所有数据。奇怪的是 scipy 方法适用于我数据集中的其他文件,但不适用于这个文件。也许我不理解这两种读取方法与 numpy 和 scipy 之间的区别。在使用任一方法读取文件时,有没有办法隔离 headers (dtype=np.int32
) 和数据 (dtype=np.float32
)?
np.fromfile 采用 "count" 参数,指定要读取的项目数。如果您事先知道 header 中的整数个数,那么无需任何类型转换即可执行所需操作的简单方法就是将 header 读取为整数,然后读取文件的其余部分作为浮动:
with open('filepath','r') as f:
header = np.fromfile(f, dtype=np.int, count=number_of_integers)
data = np.fromfile(f, dtype=np.float32)
@DavidTrevelyan 有一个很好的方法。另一种方法是结合使用 fortranfile
包和 struct
。这两种方式都不是理想的,但 scipy 的 FortranFile
.
也不是
至少这样你可以读取混合类型的数据。这是一个例子:
from fortranfile import FortranFile
from struct import unpack
with FortranFile(to_open) as fh:
dat = fh.readRecord()
val_list = unpack('=4i20d'.format(ln), dat)
您可以使用 pip install fortranfile
安装它。 struct
是标准的,(un)pack 格式是 here.
我正在尝试读取一个 Fortran 文件,其中 headers 作为整数,然后将实际数据作为 32 位浮点数。使用 numpy 的 fromfile('mydatafile', dtype=np.float32)
它将整个文件读取为 float32,但我需要 headers 在 int32 中作为我的输出文件。使用 scipy 的 FortranFile,它读取 headers:
f = FortranFile('mydatafile', 'r')
headers = f.read_ints(dtype=np.int32)
但当我这样做时:
data = f.read_reals(dtype=np.float32)
它 returns 一个空数组。我知道它不应该为空,因为它使用 numpy 的 fromfile 读取所有数据。奇怪的是 scipy 方法适用于我数据集中的其他文件,但不适用于这个文件。也许我不理解这两种读取方法与 numpy 和 scipy 之间的区别。在使用任一方法读取文件时,有没有办法隔离 headers (dtype=np.int32
) 和数据 (dtype=np.float32
)?
np.fromfile 采用 "count" 参数,指定要读取的项目数。如果您事先知道 header 中的整数个数,那么无需任何类型转换即可执行所需操作的简单方法就是将 header 读取为整数,然后读取文件的其余部分作为浮动:
with open('filepath','r') as f:
header = np.fromfile(f, dtype=np.int, count=number_of_integers)
data = np.fromfile(f, dtype=np.float32)
@DavidTrevelyan 有一个很好的方法。另一种方法是结合使用 fortranfile
包和 struct
。这两种方式都不是理想的,但 scipy 的 FortranFile
.
至少这样你可以读取混合类型的数据。这是一个例子:
from fortranfile import FortranFile
from struct import unpack
with FortranFile(to_open) as fh:
dat = fh.readRecord()
val_list = unpack('=4i20d'.format(ln), dat)
您可以使用 pip install fortranfile
安装它。 struct
是标准的,(un)pack 格式是 here.