【发布时间】:2014-03-12 14:43:31
【问题描述】:
我想将 numpy.savetxt 的结果加载到一个字符串中。基本上没有中间文件的以下代码:
import numpy as np
def savetxts(arr):
np.savetxt('tmp', arr)
with open('tmp', 'rb') as f:
return f.read()
【问题讨论】:
我想将 numpy.savetxt 的结果加载到一个字符串中。基本上没有中间文件的以下代码:
import numpy as np
def savetxts(arr):
np.savetxt('tmp', arr)
with open('tmp', 'rb') as f:
return f.read()
【问题讨论】:
对于 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() 工作。有什么想法吗?
【讨论】:
你可以使用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'
>>>
【讨论】:
StringIO,但它适用于使用python3 的BytesIO。你知道为什么它不起作用吗?
看看 array_str 或 array_repr:http://docs.scipy.org/doc/numpy/reference/routines.io.html
【讨论】:
numpy.set_printoptions 调整他们的输出,但这感觉就像是 hack。
只需要将以前的带有解码的答案扩展为 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')
【讨论】: