[Numpy-discussion] example reading binary Fortran file
Ryan May
rmay31 at gmail.com
Fri Jan 30 13:11:57 EST 2009
David Froger wrote:
> import numpy as np
>
> nx,ny = 2,5
>
> fourBytes = np.fromfile('uxuyp.bin', count=1, dtype=np.float32)
> ux = np.fromfile('uxuyp.bin', count=nx*ny,
> dtype=np.float32).reshape((nx,ny), order='F')
>
> print ux
> #===============================================
>
> I get :
>
> [[ 1.12103877e-43 1.11000000e+02 1.12000000e+02 1.13000000e+02
> 1.14000000e+02]
> [ 1.01000000e+02 1.02000000e+02 1.03000000e+02 1.04000000e+02
> 1.05000000e+02]]
>
>
> this function do the trick, but is it optimized?
>
> #===============================================
> def lread(f,fourBeginning,fourEnd,
> *tuple):
> from struct import unpack
> """Reading a Fortran binary file in litte-endian"""
>
> if fourBeginning: f.seek(4,1)
> for array in tuple:
> for elt in xrange(array.size):
> transpose(array).flat[elt] =
> unpack(array.dtype.char,f.read(array.itemsize))[0]
> if fourEnd: f.seek(4,1)
> #===============================================
I'm not sure about whether or not its optimized, but I can tell you that the
"mystery" 4 bytes are the number of bytes it that wrote out followed by that
number of bytes of data.
Ryan
--
Ryan May
Graduate Research Assistant
School of Meteorology
University of Oklahoma
More information about the NumPy-Discussion
mailing list