Numpy savetxt to a string

You can use StringIO (or cStringIO):

This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).

The description of the module says it all. Just pass an instance of StringIO to np.savetxt instead of a filename:

>>> s = StringIO.StringIO()
>>> np.savetxt(s, (1,2,3))
>>> s.getvalue()
'1.000000000000000000e+00\n2.000000000000000000e+00\n3.000000000000000000e+00\n'
>>>

For Python 3.x you can use the io module:

>>> import io
>>> s = io.BytesIO()
>>> np.savetxt(s, (1, 2, 3), '%.4f')
>>> s.getvalue()
b'1.0000\n2.0000\n3.0000\n'

>>> s.getvalue().decode()
'1.0000\n2.0000\n3.0000\n'

Note: I couldn't get io.StringIO() to work. Any ideas?

Tags:

Python

Numpy