[Numpy-discussion] using FortranFile to read data from a binary Fortran file

Brennan Williams brennan.williams@visualreservoir....
Tue Nov 3 20:18:13 CST 2009


Brennan Williams wrote:
> Hi
>
> I'm using FortranFile on 32 bit XP.
>
> The first record in the file has both 32 bit integer values and double 
> precision float values.
>
> I've used readInts('i') to read the data into what I presume is a 32-bit 
> integer numpy array.
>
> Items 0 and 1 of the array are the first double precision value.
>
> What's the best way to convert/cast these to get the double precision 
> float value?
>
> I assume I need to do some sort of dpval=ival.astype('float64')
>
> so far....
>
> f= FortranFile(fname,endian='<')
> ihdr=f.readInts('i')
>
>   
ok I took a closer look at FortranFile and I'm now doing the following. 
Note that the first line in the file I'm reading
has two double precision reals/floats followed by 8 32 bit integers.

      f=FortranFile(fullfilename,endian='<')
      if f:
        hdr=f.readString()
        print 'hdr=',hdr
        print 'len=',len(hdr)
        t=struct.unpack('<2d',hdr[0:16])
        print 't=',t
        i=struct.unpack('<8i',hdr[16:])
        print 'i=',i

This gives me...

len=48
t=(0.0,2000.0)
i=(0,0,0,5,0,0,1,213)

which is correct.

So is that the best way to do it, i.e. if I have a line of mixed data 
types, use readString and then do my own unpacking?

Brennan






More information about the NumPy-Discussion mailing list