Convert StringIO to string

Brian Quinlan brian at sweetapp.com
Mon Oct 16 15:23:40 CEST 2006


Jonathan Bowlas wrote:
> Ahh thanks, I'll give that a try.
> 
> -----Original Message-----
> From: python-list-bounces+info=jonbowlas.com at python.org
> [mailto:python-list-bounces+info=jonbowlas.com at python.org] On Behalf Of
> skryskalla at gmail.com
> Sent: 16 October 2006 14:00
> To: python-list at python.org
> Subject: Re: Convert StringIO to string
> 
> Jonathan Bowlas wrote:
>> But obviously replace() isn't an attribute of StringIO so I guess I need
> to
>> convert it to a string first, can someone please advise how I can do this?
> 
> StringIO objects are file-like objects, so you need to use read or
> readlines to get the string data out of it (just like a regular file).
> Before reading remember to seek back to the beginning to get all of the
> data ("Be kind, rewind!"):
> 
>>>> import StringIO
>>>> s = StringIO.StringIO()
>>>> s.write("hello world\n")
>>>> s.seek(0)
>>>> s.read()
> 'hello world\n'

Or, instead of seak/read, just do

 >>> s.getvalue()

Cheers,
Brian





More information about the Python-list mailing list