Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I resolve TypeError with StringIO in Python 2.7?

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
like image 797
Amit Verma Avatar asked Mar 11 '14 04:03

Amit Verma


People also ask

What is the use of StringIO in Python?

The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty.


2 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.

like image 139
Justin O Barber Avatar answered Oct 06 '22 00:10

Justin O Barber


Rather use (fixes this exact issue for me):

from StringIO import StringIO 
like image 20
jtlz2 Avatar answered Oct 05 '22 23:10

jtlz2