Newbie Q: (NumPy) how to write an array in a file ?

Nicolas Decoster Nicolas.Decoster at Noveltis.fr
Tue Oct 10 13:33:09 EDT 2000


Tony Sideris wrote:
> 
> "Nicolas Decoster" <Nicolas.Decoster at Noveltis.fr> wrote in message
> news:39E33793.ADEDAAEC at Noveltis.fr...
> > Hi !
> >
> > First, I must say that it is my first steps in Python and NumPy.
> >
> > I want to write an array in a file in binary format. Is there something
> > as simple and as _fast_ as 'fwrite' from C ?
> >
> > I don't find anything like that in the documentation. I need something
> > that is portable, so I think that pickle will not work.
> >
> > Thanks for help.
> >
> > Nicolas.
> 
> use the 'struct' module with pack for writing, and unpack for reading for
> instance.
> 
> ##    Untested
> import struct;
> file = open('file', 'wb'); ## open output file for binary write
> file.write(struct.pack('bb', 0, 1)); ## write 0 and 1 to file (in bytes)
> file.close();
> 
> to read the file back in use file.read() and struct.unpack()

I haven't tested this solution yet, but I guess that it must be a bit
long compared to a "simple" call to fwrite C-function. And I guess it
uses lots of memory in case of very big arrays.

By a rapid inspection of NumPy C sources, I found a comment about array
writing. This comment contains an old writing function for arrays
(array_print) that actually uses a 'fwrite'. The comment begins with

/* No longer implemented here.  Use the default in object.c
static int array_print(PyArrayObject *self, FILE *fp, int flags) {
... */

I have no access to file object.c. But this must contains what I need,
at least if there is a python function that is "connected" to this.

Thanks in advance for any suggestion.

Nicolas.

--
Tél. : 00 (33) 5 62 88 11 16
Fax  : 00 (33) 5 62 88 11 12
Nicolas.Decoster at Noveltis.fr

Noveltis
Parc Technologique du Canal
2, avenue de l'Europe
31520 Ramonville Saint Agne - France



More information about the Python-list mailing list