Re: Reading floating point data with Python

Steven D. Majewski (sdm7g@elvis.med.Virginia.EDU)
Mon, 4 Apr 1994 17:07:13 GMT

In article <2nn4pe$ksd@news.umbc.edu>,
L. Larrabee Strow <strow@umbc.edu> wrote:
>Is there any existing way to read files containing binary floating
>point data with Python?
>
>It sure would be nice to have fread/fwrite type capabilities.
>Reformatting floating point data files to ascii, reading them , and
>using atof is not an option due to space and performance problems.
>

Look at builtin modules array and struct.

>>> from array import array
>>> a = array( 'f' )

Will create an extendible floating point array with methods:

['append', 'byteswap', 'fromfile', 'fromlist', 'fromstring',
'insert', 'read', 'reverse', 'tofile', 'tolist', 'tostring', 'write']

Arrays also have __getitem__ and __setitem__ methods defined, so you
can access their elements just like lists.

a[0] is the first element; a[-1] is the last.
( "a = array( 'f' )" creates an empty array, so, just as for an empty
list [], a[0] will generate an IndexError. a = array( 'f', [1,2,3] )
will create an array initialized with three values. )

a.fromfile( open( filename, 'r' ) , 1000 )
will read in 1000 binary values from filename into array a.
( fromfile, fromstring, and fromlist all append values to the end
of the array, extending it's size. )

module struct has functions calcsize, pack and unpack, which
can convert to/from non-homogeneous binary structures.

>>> unpack( '5f', array( 'f', range(5) ).tostring() )
(0.0, 1.0, 2.0, 3.0, 4.0)

For some files of mixed data, you may want to alternate the use of
array.fromfile() and unpack( fmt, file.read( calcsize( fmt ) )

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics