wxcoder wxcoder - 1 year ago 187
Python Question

Python: Reading Fortran Binary file using numpy or scipy

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)

but when I do:

data = f.read_reals(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 (
) and data (
) when reading in the file with either method?

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download