469,949 Members | 2,696 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,949 developers. It's quick & easy.

StringIO.readline() returns ''

Max
I'm using StringIO for the first time (to buffer messages recieved from
a socket). I thought it would be a simple matter of writing the stuff to
the buffer and then calling readline, but that doesn't seem to work:
buf = StringIO.StringIO()
buf.write("Foo\n")
buf.write("Bar\n")
buf.flush()
buf.readline()

''

I expected buf.readline() to return 'Foo\n'. What am I doing wrong?

--Max
Apr 9 '06 #1
3 6878
"Unknown" wrote:
I'm using StringIO for the first time (to buffer messages recieved from
a socket). I thought it would be a simple matter of writing the stuff to
the buffer and then calling readline, but that doesn't seem to work:
>>> buf = StringIO.StringIO()
>>> buf.write("Foo\n")
>>> buf.write("Bar\n")
>>> buf.flush()
>>> buf.readline() ''

I expected buf.readline() to return 'Foo\n'. What am I doing wrong?


you forgot to rewind the file:
buf = StringIO.StringIO()
buf.write("Foo\n")
buf.write("Bar\n")
buf.seek(0)
buf.readline()

'Foo\n'

</F>

Apr 9 '06 #2
Max
Fredrik Lundh wrote:
you forgot to rewind the file:

Thank you.

</F>


--Max
Apr 9 '06 #3
You can also just type buf.getvalue() which returns the current
StringIO buffer as a python string, without the rewinding

Apr 10 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Christoph | last post: by
5 posts views Thread by Leif K-Brooks | last post: by
6 posts views Thread by Christian Convey | last post: by
21 posts views Thread by Paul Rubin | last post: by
2 posts views Thread by Jonathan Bowlas | last post: by
3 posts views Thread by bob | last post: by
reply views Thread by 7stud | last post: by
reply views Thread by dimitri pater | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.