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

编程入门 行业动态 更新时间:2024-10-28 01:26:25
本文介绍了无法在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()获取数据

本文发布于:2023-08-05 11:16:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1305182.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   python   StringIO   read

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!