[Tutor] Fwd: help on StringIO

W W srilyk at gmail.com
Mon May 26 14:20:56 CEST 2008


---------- Forwarded message ----------
From: W W <srilyk at gmail.com>
Date: Mon, May 26, 2008 at 7:18 AM
Subject: Re: [Tutor] help on StringIO
To: inhahe <inhahe at gmail.com>


On Mon, May 26, 2008 at 5:06 AM, inhahe <inhahe at gmail.com> wrote:
> Can someone explain to me how to use StringIO?

>>>> import StringIO
>>>> s = StringIO.StringIO()
>>>> s.write('hi')
>>>> print s.read()
>
>>>>
>
> Is this a bug?

>From what I read in the docs, .read() usually reads from the current
position. So basically you're inputting 'hi' and the cursor is at the
end: 'hi_'

So when you read from the _ the only thing that's left is a blank string ''.

Instead, try this:
>>> import StringIO
>>> s = StringIO.StringIO()
>>> s.write('hi')
>>> print s.getvalue()
hi
>>> s.read()
''
>>>

As you can see, s.read() works just the same, but s.getvalue() will
get the actual value, regardless of your position in the "file".

(I could be completely off with the read bit, so if anyone knows
better, feel free to correct)

Look here for more help:
http://docs.python.org/lib/module-StringIO.html

HTH,
Wayne


--
To be considered stupid and to be told so is more painful than being
called gluttonous, mendacious, violent, lascivious, lazy, cowardly:
every weakness, every vice, has found its defenders, its rhetoric, its
ennoblement and exaltation, but stupidity hasn't. - Primo Levi



-- 
To be considered stupid and to be told so is more painful than being
called gluttonous, mendacious, violent, lascivious, lazy, cowardly:
every weakness, every vice, has found its defenders, its rhetoric, its
ennoblement and exaltation, but stupidity hasn't. - Primo Levi


More information about the Tutor mailing list