将Numpy savetxt保存为字符串
我想把numpy.savetxt的结果加载到一个字符串里。也就是说,我想要的效果是下面这段代码,但不想生成中间的文件:
import numpy as np
def savetxts(arr):
np.savetxt('tmp', arr)
with open('tmp', 'rb') as f:
return f.read()
4 个回答
0
只需要在之前的回答基础上,加上将数据解码为UTF8,这样就能生成一个字符串。这对于把数据导出为人类可读的文本文件非常有用。
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')
0
看看 array_str 或 array_repr 这两个东西:http://docs.scipy.org/doc/numpy/reference/routines.io.html
10
对于Python 3.x,你可以使用io
这个模块:
>>> 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'
注意:我没能让io.StringIO()
正常工作。有没有什么好的建议?
5
你可以使用 StringIO(或者 cStringIO):
这个模块实现了一个像文件一样的类,叫做 StringIO,它可以读写一个字符串缓冲区(也就是内存文件)。
这个模块的描述已经说得很清楚了。只需要把一个 StringIO
的实例传给 np.savetxt
,而不是传一个文件名:
>>> s = StringIO.StringIO()
>>> np.savetxt(s, (1,2,3))
>>> s.getvalue()
'1.000000000000000000e+00\n2.000000000000000000e+00\n3.000000000000000000e+00\n'
>>>