11

I would like to load the result of numpy.savetxt into a string. Essentially the following code without the intermediate file:

import numpy as np

def savetxts(arr):
    np.savetxt('tmp', arr)
    with open('tmp', 'rb') as f:
        return f.read()

4 Answers 4

10

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?

Sign up to request clarification or add additional context in comments.

Comments

6

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'
>>>

2 Comments

As mentioned by @Tom-pohl, It does not work with StringIO but it works with BytesIO using python3. Do you have an idea about why it does not work ?
@Ger Sorry, I have not much experience with python3.
0

Have a look at array_str or array_repr: http://docs.scipy.org/doc/numpy/reference/routines.io.html

1 Comment

By default, both functions shorten their output which is typically not what you want. You can tweak their output using numpy.set_printoptions, but that feels like a hack.
0

Just requires extending previous answers with decode to UTF8 in order to generate a string. Very useful for exporting data to human readable text files.

import io
import numpy as np

s = io.BytesIO()

np.savetxt(s, np.linspace(0,10, 30).reshape(-1,3), delim=',' '%.4f')
outStr = s.getvalue().decode('UTF-8')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.