wxcoder - 10 months ago 68

Python Question

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)`

`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 (

`dtype=np.int32`

`dtype=np.float32`

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)
```