StringIO readline() bug??

Alex Martelli aleaxit at yahoo.com
Fri Oct 13 06:21:37 EDT 2000


"Chris Arai" <chris at araidesign.com> wrote in message
news:39E6CC82.F7A1711A at araidesign.com...
    [snip]
> >>>fstr=StringIO(file.readlines())

Here's your error: StringIo needs to be initialized with
a string, not with a list of strings, which is what you're
giving it here.


Use, instead:

>>> fstr = StringIO(file.readline())

and everything should work fine.


Note the difference: file.readline() returns the file's
contents as a single string; file.readlines() returns
it as a list of strings (one per line).

If you DID have a list-of-strings already through some
other process, and wanted to build a StringIO object
from it, you would concatenate the list into a string
when initializing the StringIO object.

If the strings in the list already have the needed
'\n' (as they do when coming from .readlines():

    fstr = StringIO(''.join(thelistofstrings))

If the strings in the list are bereft of '\n', and
you want to interpose '\n' between each of them:

    fstr = StringIO('\n'.join(thelistofstrings))


Alex






More information about the Python-list mailing list