在python中使用StringIO的read()获取数据失败

2024-05-08 03:09:22 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python2.7版本。下面是我的示例代码。

import StringIO
import sys

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

在上面的程序中,read()不返回任何内容,而as getvalue()返回“hello”。有人能帮我解决这个问题吗?我需要read(),因为下面的代码涉及读取“n”字节。


Tags: 代码import程序版本示例内容helloread
2条回答
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'

您需要将缓冲区位置重置为起始位置。您可以通过执行buff.seek(0)来完成此操作。

每次读或写缓冲区时,位置都会提前一位。假设你从一个空缓冲区开始。

缓冲区值为"",缓冲区位置为0。 你可以buff.write("hello")。显然,缓冲区值现在是hello。但是,缓冲区位置现在是5。当您调用read()时,没有超过位置5的内容可供读取!所以它返回一个空字符串。

相关问题 更多 >