numpy savetxt到一个字符串 [英] Numpy savetxt to a string

查看:793
本文介绍了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,该类可读写字符串缓冲区(也称为内存文件).

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

该模块的说明说明了一切.只需将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到一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆