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

Neil Martinsen-Burrell nmb at wartburg.edu
Wed Nov 4 12:43:33 EST 2009


On 2009-11-03 20:18 , Brennan Williams wrote:
> 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?

That's correct.  FortranFile works most readily with records (equivalent 
to individual write statements) that are of uniform types and 
precisions.  This is a leftover from the way that my own Fortran codes 
were doing I/O.  To solve the problem correctly in FortranFile requires 
a way to specify the sequence of types to expect in a single record. 
This could then give the equivalent of what you have done above, which 
could also be written in a single unpack call

ans = struct.unpack('<2d8i',hdr); t=ans[:2];i=ans[2:])

The readString method just takes care of stripping off and 
error-checking the record length information that fortran unformatted 
I/O often uses.  I don't have much opportunity to work on Fortran 
unformatted I/O these days, but I would gladly accept any contributions.

-Neil




More information about the NumPy-Discussion mailing list