使用Python2.7版本.下面是我的示例代码.
Using Python2.7 version. Below is my sample code.
import StringIO import sys buff = StringIO.StringIO() buff.write("hello") print buff.read()在上面的程序中,read()没有给我任何回报,而getvalue()却给我你好".谁能帮我解决这个问题?我需要read(),因为我的以下代码涉及读取"n"个字节.
in the above program, read() returns me nothing where as getvalue() returns me "hello". Can anyone help me out in fixing the issue? I need read() because my following code involves reading "n" bytes.
推荐答案您需要将缓冲区位置重置为开头.您可以通过执行buff.seek(0)来做到这一点.
You need to reset the buffer position to the beginning. You can do this by doing buff.seek(0).
每次读取或写入缓冲区时,该位置都会前移一个.假设您从一个空的缓冲区开始.
Every time you read or write to the buffer, the position is advanced by one. Say you start with an empty buffer.
缓冲区值是"",缓冲区pos是0. 您执行buff.write("hello").显然,缓冲区值现在为hello.但是,缓冲区位置现在为5.调用read()时,没有位置5可以读取!因此它返回一个空字符串.
The buffer value is "", the buffer pos is 0. You do buff.write("hello"). Obviously the buffer value is now hello. The buffer position, however, is now 5. When you call read(), there is nothing past position 5 to read! So it returns an empty string.
更多推荐
无法在python中使用StringIO的read()获取数据
发布评论