Python:使用numpy或scipy读取Fortran二进制文件 [英] Python: Reading Fortran Binary file using numpy or scipy

查看:220
本文介绍了Python:使用numpy或scipy读取Fortran二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取一个Fortran文件,其标头为整数,然后将实际数据作为32位浮点数.使用numpy的fromfile('mydatafile', dtype=np.float32)它将整个文件读取为float32,但我需要将头文件的输出文件放在int32中.使用scipy的FortranFile读取标头:

I am trying to read a fortran file with headers as integers and then the actual data as 32 bit floats. Using numpy's fromfile('mydatafile', dtype=np.float32) it reads in the whole file as float32 but I need the headers to be in int32 for my output file. Using scipy's FortranFile it reads the headers:

f = FortranFile('mydatafile', 'r')
headers = f.read_ints(dtype=np.int32)

但是当我这样做时:

data = f.read_reals(dtype=np.float32)

它返回一个空数组.我知道它不应该为空,因为使用numpy的fromfile会读取所有数据.奇怪的是,scipy方法可用于数据集中的其他文件,但不适用于此文件.也许我不理解numpy和scipy这两种读取方法之间的区别.用任何一种方法读取文件时,是否有办法隔离标头(dtype=np.int32)和数据(dtype=np.float32)?

it returns an empty array. I know it shouldn't be empty because using numpy's fromfile it reads all of the data. Oddly enough the scipy method worked for other files in my dataset, but not this one. Perhaps i'm not understanding the difference between each of the two read methods with numpy and scipy. Is there a way to isolate the headers (dtype=np.int32) and data (dtype=np.float32) when reading in the file with either method?

推荐答案

np.fromfile takes a "count" argument, which specifies how many items to read. If you know the number of integers in the header in advance, a simple way to do what you want without any type conversions would just be to read the header as integers, followed by the rest of the file as floats:

with open('filepath','r') as f:
    header = np.fromfile(f, dtype=np.int, count=number_of_integers)
    data = np.fromfile(f, dtype=np.float32)

这篇关于Python:使用numpy或scipy读取Fortran二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆