Re: Reading floating point data with Python

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Mon, 11 Apr 1994 12:44:54 -0400

On Apr 10, 14:19, Mike Tibbs wrote:
> Message-Id: <1994Apr10.141917.13804@esseye.si.com>
> In article <CnqvK2.KBG@murdoch.acc.Virginia.EDU>, sdm7g@elvis.med.Virginia.EDU
> (Steven D. Majewski) writes:
> |> 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?
> |> >
> |>
> |> Look at builtin modules array and struct.
> |>
[ ... ]
> |>
> |> 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. )
>
> What is the format of 'filename' exactly? Is it just a stream of binary
> floating point values?
>

YES. ( If that's all you read-from/write-to it ).

> How would you create such a file in python?

In python, strings can contain non-ascii characters including
zero bytes. Any python object that can be converted to a
(binary) string can be written out, so there are several ways
to create and read binary files.

from array import array
a = array( 'f', range( 200 ) )
# creates array with values [ 0.0, 1.0, 2.0, ... 199.0 ]
astr = a.tostring( ) # returns the binary string of bytes
file = open( 'floats.tmp', 'w' )
file.write( astr ) # write it out...
a.tofile( file ) # write it out again ...
file.close()
b = array( 'f' )
b.fromfile( open( 'floats.tmp', 'r' ), 400 ) # reads both into b
c = array( 'f' )
c.fromstring( open( 'floats.tmp', 'r' ).read( 400*4 ) ) # same for c

If you have file of non homogeneous binary values, you can use module
struct, which takes a sequence of format characters to convert to/from
binary char strings and tuples of values.

struct.unpack( 'ii2f', 0, 1, 0.0, 1000.0 )

-- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU> --
-- UVA Department of Molecular Physiology and Biological Physics --
-- Box 449 Health Science Center Charlottesville,VA 22908 --