无法在python中使用StringIO的read()获取数据 [英] Fail to get data on using read() of StringIO in python

查看:179
本文介绍了无法在python中使用StringIO的read()获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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()获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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