How can I resolve TypeError with StringIO in Python 2.7?

Question:

Trying to read following string as file using StringIO but getting the error below. How can I resolve it?

>> from io import StringIO
>>>
>>> datastring = StringIO("""
... Country  Metric           2011   2012   2013  2014
... USA     GDP               7      4     0      2
... USA     Pop.              2      3     0      3
... GB      GDP               8      7     0      7
... GB      Pop.              2      6     0      0
... FR      GDP               5      0     0      1
... FR      Pop.              1      1     0      5
... """)
Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
TypeError: initial_value must be unicode or None, not str
Asked By: Amit

||

Answers:

You can resolve the error by simply adding a u before your string to make the string unicode:

datastring = StringIO(u"""
Country  Metric           2011   2012   2013  2014
USA     GDP               7      4     0      2
USA     Pop.              2      3     0      3
GB      GDP               8      7     0      7
GB      Pop.              2      6     0      0
FR      GDP               5      0     0      1
FR      Pop.              1      1     0      5
""")

Your initial value should be unicode.

Answered By: Justin O Barber

Rather use (fixes this exact issue for me):

from StringIO import StringIO
Answered By: jtlz2
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.