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

raj picture raj · Apr 22, 2012 · Viewed 21.6k times · Source

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.

Answer

Joel Cornett picture Joel Cornett · Apr 22, 2012

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.