在Python中使用StringIO的read()方法无法获取数据

81

使用Python 2.7版本。以下是我的示例代码。

import StringIO
import sys

buff = StringIO.StringIO()
buff.write("hello")
print buff.read()

在上面的程序中,read()返回了空值,而getvalue()返回了“hello”。有人能帮我解决这个问题吗?我需要使用read(),因为我的后续代码涉及读取“n”个字节。


stringIO中没有名为read()的函数。 - hjpotter92
@ChasingDeath:是的,有的。尝试使用dir(StringIO.StringIO) - Joel Cornett
2
StringIO可以将字符串转换为文件对象,因此自然会有read()方法。 - jamylak
2个回答

116
你需要将缓冲区位置重置为开头。你可以通过执行 buff.seek(0) 来实现。
每次读写缓冲区时,位置都会向前移动一位。比如你从一个空的缓冲区开始:
缓冲区的值为 "" ,缓冲区位置为 0。 你执行 buff.write("hello")。显然,缓冲区的值现在是hello。但是,缓冲区位置现在是 5。当你调用 read() 时,已经没有超过位置 5 的内容可供读取了!因此,它返回一个空字符串。

28
In [38]: out_2 = StringIO.StringIO('not use write') # be initialized to an existing string by passing the string to the constructor

In [39]: out_2.getvalue()
Out[39]: 'not use write'

In [40]: out_2.read()
Out[40]: 'not use write'
或者
In [5]: out = StringIO.StringIO()

In [6]: out.write('use write')

In [8]: out.seek(0)

In [9]: out.read()
Out[9]: 'use write'

1
out.seek(0) 是我在尝试将 pickle 转储到 StringIO 并上传到 S3 时遗漏的一步。一旦我将其推回开头,我的 S3 对象就会被正确填充。 - Matthew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接