numpy - save many arrays into a file object

Peter Otten __peter__ at web.de
Wed Jun 30 12:47:31 EDT 2010


Laszlo Nagy wrote:

> import numpy
> data = numpy.array(...)
> numpy.save("test.np",data)
> 
> This is very good, but I want to save the data into a file object with a
> write() method. E.g. not a real file. (My purpose right now is to save
> many arrays into one binary file, while recording starting positions of
> the arrays.)
> 
> How can I do that?

numpy.save() accepts file(-like) objects, the help is quite clear about 
that:

"""
save(file, arr)
    Save an array to a binary file in NumPy format.

    Parameters
    ----------
    f : file or string
        File or filename to which the data is saved.  If the filename
        does not already have a ``.npy`` extension, it is added.
    x : array_like
        Array data.
"""

>>> import numpy
>>> from StringIO import StringIO
>>> stream = StringIO()
>>> a = numpy.array([1,2,3])
>>> b = numpy.array([10, 11])
>>> numpy.save(stream, a)
>>> pos = stream.tell()
>>> numpy.save(stream, b)
>>> stream.seek(0)
>>> stream.seek(pos)
>>> numpy.load(stream)
array([10, 11])
>>> stream.seek(0)
>>> numpy.load(stream)
array([1, 2, 3])

Peter



More information about the Python-list mailing list