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
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.
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.
Rather use (fixes this exact issue for me):
from StringIO import StringIO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With