本文介绍了numpy savetxt到一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将numpy.savetxt的结果加载到字符串中.本质上,以下代码不包含中间文件:
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()
推荐答案
您可以使用 StringIO (或cStringIO):
You can use StringIO (or cStringIO):
该模块的说明说明了一切.只需将StringIO
的实例传递给np.savetxt
而不是文件名:
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'
>>>
这篇关于numpy savetxt到一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!