[SciPy-user] writing a binary file

Travis Oliphant oliphant at ee.byu.edu
Thu Jan 23 14:05:47 EST 2003


>
> How do I write a float array to a binary file?
> There is a
> readFloatArray()
> in Module Scientific, but not an equivalent
> writeFloatArray(), while writeArray()
> writes an ascii file.
>

Look at the io subpackge.  There are all kinds of techniques for saving
binary data.

You can use Pickle to write the Python Object to a file.

You can use fid = io.fopen() and fid.write(a) where a is a Numeric array
to write to a file.

Thus,

fid = io.fopen('myfile.dat','w')
fid.write(a)
fid.close()

will write the array a to the file 'myfile.dat'

as a linear stream of bytes.

This does not store information about the structure of the array, however.
It's main purpose is to interface with binary files directly.


If you want the data to be stored for a later Python session use Pickle

import cPickle

cPickle.dump(a, 'myfile.pkl', 1)  # write the object to the file (binary)

a = cPickle.load('myfile.pkl')  # read the object back from the file.

This preserves the object.

a can be just about any kind of Python object (a dictionary of Numeric
arrays, for example).

So, if you are only saving data from Python for reading back into Python.
cPickle in the standard library is the way to go.

The io subpackage in scipy is available for interfacing to other file
formats.

-teo


-- 
Travis Oliphant
Assistant Professor
459 CB
Electrical and Computer Engineering
Brigham Young University
Provo, UT 84602
Tel: (801) 422-3108
oliphant.travis at ieee.org




More information about the SciPy-User mailing list