[Tutor] help on StringIO

Kent Johnson kent37 at tds.net
Mon May 26 18:33:40 CEST 2008


On Mon, May 26, 2008 at 6:06 AM, inhahe <inhahe at gmail.com> wrote:
> Can someone explain to me how to use StringIO?
>
> Python 2.5.2 Stackless 3.1b3 060516 (release25-maint, Apr  2 2008, 19:04:14) [MS
> C v.1310 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import StringIO
>>>> s = StringIO.StringIO()
>>>> s.write('hi')
>>>> print s.read()

Just like when writing to a real file, if you want to read back what
you just wrote, you have to seek first:

In [1]: import StringIO

In [2]: s=StringIO.StringIO()

In [3]: s.write('hi')

In [4]: s.seek(0)

In [5]: s.read()
Out[5]: 'hi'

But for the common use of StringIO where you want to write to a
file-like object and retrieve what is written, just use getvalue().

Kent


More information about the Tutor mailing list