[Tutor] I don't understand example 12.10.2

Magnus Lyckå magnus@thinkware.se
Sat May 10 14:21:21 2003


At 07:23 2003-05-10 -0400, Daniel Nash wrote:
>data = StringIO.StringIO()

You can see a StringIO object as an in-memory file.
See below:

 >>> import StringIO
 >>> m = StringIO.StringIO()
 >>> m.write('Hello, there!\n')
 >>> m.write('How are you?\n')
 >>> m.write('I\'m fine\n')
 >>> m.readlines()
[]
 >>> m.tell()
36
 >>> m.seek(0)
 >>> m.tell()
0
 >>> m.readlines()
['Hello, there!\n', 'How are you?\n', "I'm fine\n"]

It also has some features files lack, e.g.
 >>> m.getvalue()
"Hello, there!\nHow are you?\nI'm fine\n"

The data isn't saved in a file, but the interface is
almost exactly like the interface to a file. This means
that functions that expect a file object can usually take
a StringIO object instead.

Note that StringIO is written in Python, and there is
an almost identical module called cStringIO which is
written in C and thus much faster. I think cStringIO
lacks some (not often used) features of StringIO, but
it's typically the module people use...


--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program