[Numpy-discussion] example reading binary Fortran file

Gary Ruben gruben@bigpond.net...
Fri Jan 30 18:00:20 CST 2009

The only time I've done this, I used numpy.fromfile exactly as follows. 
The file had a header followed by a number of records (one float 
followed by 128 complex numbers), requiring separate calls of 
numpy.fromfile to read each part. The only strange part about this was 
that the Fortran code was only supposed to be outputting 3 header fields 
but was adding an extra integer field for some unknown reason. I used a 
binary file viewer to work out the actual format of the file. To get at 
just the complex data in the records, I viewed the data as a recarray. 
Hopefully it's reasonably self-explanatory:


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

f = open("field.dat",'rb')

# Read header
a = np.fromfile(f, np.dtype([('f1','<i4'), ('f2','<i4'), ('f3','<f8'),
                              ('f4','<i4')]), count = 1)

# Read data records
b = np.fromfile(f, np.dtype([('f1','<f8'), ('f2','128<c16')]))
bv = b.view(np.recarray)

plt.imshow(np.abs(np.fft.fftshift(np.fft.fft(bv.f2, axis=1), axes=[1])),
            origin='lower', interpolation='nearest', cmap=cm.Oranges)



David Froger wrote:
> Hy,
> My question is about reading Fortran binary file (oh no this question 
> again...)
> After googling, I read that fopen and npfille was deprecated, and we 
> should use numpy.fromfile and ndarray.tofile, but despite of the 
> documentaion, the cookbook, the mailling list and google, I don't succed 
> in making a simple example. Considering the simple Fortran code below 
> what is the Python script to read the four arrrays? What about if my pc 
> is little endian and the file big endian?

More information about the Numpy-discussion mailing list