StringIO in 2.6 and beyond

Peter Otten __peter__ at web.de
Tue Dec 9 19:05:49 CET 2008


Bill McClain wrote:

> I've just installed 2.6, had been using 2.4.
> 
> This was working for me:
> 
>     #! /usr/bin/env python
>     import StringIO
>     out = StringIO.StringIO()
>     print >> out, 'hello'
> 
> I used 2to3, and added import from future to get:
> 
>     #! /usr/bin/env python
>     from __future__ import print_function
>     import io
>     out = io.StringIO()
>     print('hello', file=out)
> 
> ...which gives an error:
> 
> Traceback (most recent call last):
>   File "./example.py", line 5, in <module>
>     print('hello', file=out)
>   File "/usr/local/lib/python2.6/io.py", line 1487, in write
>     s.__class__.__name__)
> TypeError: can't write str to text stream
> 
> ...which has me stumped. Why can't it?

>>> from __future__ import print_function
>>> import io
>>> out = io.StringIO()
>>> print("hello", file=out)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/io.py", line 1487, in write
    s.__class__.__name__)
TypeError: can't write str to text stream

Seems io.StringIO() wants unicode. So let's feed it some:

>>> print(u"hello", file=out)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/io.py", line 1487, in write
    s.__class__.__name__)
TypeError: can't write str to text stream

Still complaining? Let's have a look at the output so far:

>>> out.getvalue()
u'hello'

Hmm, u"hello" was written. The complaint must be about the newline then.

>>> out = io.StringIO()
>>> print(u"hello", file=out, end=u"\n")
>>> out.getvalue()
u'hello\n'

Heureka. Let's try something else now:

>>> print(u"hello", u"world", file=out, end=u"\n")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/io.py", line 1487, in write
    s.__class__.__name__)
TypeError: can't write str to text stream

Fixing is left as exercise ;)

Peter



More information about the Python-list mailing list