Fail to get data on using read() of StringIO in python

心不动则不痛 提交于 2019-12-03 03:23:35

问题


Using Python2.7 version. Below is my sample code.

import StringIO
import sys

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

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.


回答1:


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.

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.




回答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'

or

In [5]: out = StringIO.StringIO()

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

In [8]: out.seek(0)

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


来源:https://stackoverflow.com/questions/10265593/fail-to-get-data-on-using-read-of-stringio-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!