如何在Python 2.7中使用StringIO解决TypeError?

时间:2014-03-11 04:14:02

标签: python python-2.7 stringio

尝试使用StringIO将以下字符串作为文件读取,但收到以下错误。我该如何解决?

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

2 个答案:

答案 0 :(得分:31)

您可以通过在字符串之前添加u来生成字符串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
""")

您的初始值should be unicode

答案 1 :(得分:5)

而是使用(为我修复这个问题):

from StringIO import StringIO