非常简单的代码:
import StringIO
import numpy as np
c = StringIO.StringIO()
c.write("1 0")
a = np.loadtxt(c)
print a
我得到一个空数组+警告c是一个空文件。
我通过添加:
来修复此问题d=StringIO.StringIO(c.getvalue())
a = np.loadtxt(d)
我认为这样的事情不应该发生,这里发生了什么?
答案 0 :(得分:2)
这是因为文件对象的“位置”在写入后位于文件的末尾。因此,当numpy读取它时,它会从文件的末尾读到结尾,这没什么。
寻找文件的开头然后它可以工作:
>>> from StringIO import StringIO
>>> s = StringIO()
>>> s.write("1 2")
>>> s.read()
''
>>> s.seek(0)
>>> s.read()
'1 2'
答案 1 :(得分:1)
StringIO
是一个类似文件的对象。因此,它具有与文件一致的行为。有一个文件指针的概念 - 文件中的当前位置。将数据写入StringIO
对象时,文件指针将调整为数据的末尾。当您尝试读取它时,文件指针已经位于缓冲区的末尾,因此不会返回任何数据。
要阅读它,您可以执行以下两项操作之一:
StringIO.getvalue()
。这会返回
缓冲区开头的数据,保持文件指针不变。StringIO.seek(0)
将文件指针重新定位到开头
缓冲区然后调用StringIO.read()
来读取数据。<强>演示强>
>>> from StringIO import StringIO
>>> s = StringIO()
>>> s.write('hi there')
>>> s.read()
''
>>> s.tell() # shows the current position of the file pointer
8
>>> s.getvalue()
'hi there'
>>> s.tell()
8
>>> s.read()
''
>>> s.seek(0)
>>> s.tell()
0
>>> s.read()
'hi there'
>>> s.tell()
8
>>> s.read()
''
这有一个例外。如果在创建StringIO
时提供值,缓冲区将使用值初始化,但文件指针将位于缓冲区的开头:
>>> s = StringIO('hi there')
>>> s.tell()
0
>>> s.read()
'hi there'
>>> s.read()
''
>>> s.tell()
8
这就是为什么它在你使用
时有效d=StringIO.StringIO(c.getvalue())
因为您在创建时初始化StringIO
对象,并且文件指针位于缓冲区的开头。