writing binary array to file

What's the easiest way to write a Numeric array to a file?

Easiest or best?

In the next release I've added load and save funcs for converting
arrays to and from ascii files. But this is slow and generally lossy.

Best is to use the binary string operations tostring and fromstring

    from Numeric import fromstring, Float
    # write
    file('fname.out', 'wb').write(x.tostring())

    # read
    x = fromstring(file('fname.out', 'rb').read(), Float)

    #If data is MxN you'll need to reshape
    x.shape = M,N

Hope this help,
JDH

John Hunter wrote:

Best is to use the binary string operations tostring and fromstring

    from Numeric import fromstring, Float
    # write
    file('fname.out', 'wb').write(x.tostring())

    # read
    x = fromstring(file('fname.out', 'rb').read(), Float)

    #If data is MxN you'll need to reshape
    x.shape = M,N

Hope this help,
JDH

Note that numarray has a tofile method and a fromfile function
to do this without going through the copying required by tostring
and fromstring. Like those, it also doesn't save any shape or
type info in the file.

Perry

Thanks much John & Perry! Part of my confusion was the fact that I'm
using numarray on my laptop/Windows and Numeric on Linux... and I was in
a hurry... and general ignorance. Anyway, thanks again.

Randy

···

-----Original Message-----
From: Perry Greenfield [mailto:perry@…86…]
Sent: Thursday, April 08, 2004 1:48 PM
To: John Hunter; Randy Heiland
Cc: matplotlib-users@lists.sourceforge.net
Subject: RE: [Matplotlib-users] writing binary array to file

John Hunter wrote:
> Best is to use the binary string operations tostring and fromstring
>
> from Numeric import fromstring, Float
> # write
> file('fname.out', 'wb').write(x.tostring())
>
> # read
> x = fromstring(file('fname.out', 'rb').read(), Float)
>
> #If data is MxN you'll need to reshape
> x.shape = M,N
>
> Hope this help,
> JDH
>

Note that numarray has a tofile method and a fromfile function
to do this without going through the copying required by tostring
and fromstring. Like those, it also doesn't save any shape or
type info in the file.

Perry