numpy - save many arrays into a file object

L

Laszlo Nagy

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?

Thanks

Laszlo
 
P

Peter Otten

Laszlo said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top