help / examples reading floats / doubles, user definded objs

Alex Martelli aleaxit at yahoo.com
Wed Jan 10 06:28:58 EST 2001


"Bryan Webb" <bww00 at amdahl.com> wrote in message
news:93g594$ia8 at dispatch.concentric.net...
> Alex,
>     Sorry for the vagueness. I'm red headed, we tend to have lapses.

Hey, np - though my hair is brown (with some gray these days), if I
had a penny for each time _I_'ve been vague, I'd be pretty rich:-).


> I want to read the floats/doubles from a binary file that was written from
c
> or python.

Great!  Do note that this is hard to do *cross-platform*, i.e., if the
files need to be written on any platform and read back on any other one.
But, within a single platform, your life is a bit simpler.


>  I have used the array builtin to write the data out to a binary file.

In this case, the fromfile method of array objects should serve you
just as well to read them back in -- just be sure to open the file
as 'binary' if you need this to work on such platforms as Windows.

E.g., here's a Python script that writes some floats with array:

import array

ar = array.array('f', range(6))
ar.tofile(open("foo.dat","wb"))

and here's one that reads them back and prints them:

import array

ar = array.array('f')
try:
    ar.fromfile(open("foo.dat","rb"), 999)
except EOFError: pass

for x in ar:
    print x

Note that I assume we don't know exactly how many items we
have to read, just "no more than 999" -- which is why I
need to catch EOFError explicitly: that's what .fromfile
raises (after correctly inserting what data it finds) to
let us know it has not found quite as many items as were
specified it should read.

Running these two scripts one after the other will emit
something like
0.0
1.0
2.0
3.0
4.0
5.0
to ensure us that all is working fine:-).


> I found the struct builtin module and am toying around with it... with
some
> success.
> I'll work at it some more and repost my question if i need some other
help.

struct is great, but you may not need it if what you want
to read is a file (or big stretch of it: also check out
the fromstring method) containing nothing but an array of
binary-written floats (or doubles); the array module is
then likely to prove simpler for the purpose.


Alex






More information about the Python-list mailing list