81

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.

3
  • there's no function named read() in stringIO
    – hjpotter92
    Apr 22, 2012 at 5:59
  • @ChasingDeath: Yes there is. Try dir(StringIO.StringIO). Apr 22, 2012 at 6:02
  • 2
    yeah StringIO makes a file like object for strings so of course there would be read()
    – jamylak
    Apr 22, 2012 at 6:44

2 Answers 2

116

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.

0
28
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'
1
  • 1
    out.seek(0) is what was missing for me when I was trying to dump a pickle to StringIO and upload to s3. Once I pushed back to the beginning, my s3 object would be populated properly.
    – Matthew
    Nov 17, 2017 at 19:00

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.