如何在Python 2.7中使用StringIO解决TypeError?
试图使用如何在Python 2.7中使用StringIO解决TypeError?,python,python-2.7,stringio,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.
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
>从io导入StringIO
>>>
>>>datastring=StringIO(“”)\
…国家计量单位2011 2012 2013 2014
…美国国内生产总值7402
…美国流行音乐2 3 0 3
…GB GDP 8707
…GB流行音乐2.6 0 0
…法国国内生产总值500 1
…FR Pop.1 10 5
... """)
回溯(最近一次呼叫最后一次):
文件“”,第9行,在
TypeError:初始值必须是unicode或None,而不是str
您只需在字符串前添加一个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
""")
您的初始值。而是使用(为我解决了这个问题):
@JustinBarber-如果数据字符串已设置为变量,并且必须从
StringIO()
开始,该怎么办<代码>unicode(变量)。回答了我自己的问题。谢谢。我将代码从python3.6转换为python2.7,忘记了从io导入StringIO的导入语句。当我看到这一点时,我记得对于python3,我不能使用“from StringIO”。在我的例子中,“从io导入BytesIO”是有效的,但OP被标记为python-2.x@Tobiaszanket整个主题是一个雷区:-\
from StringIO import StringIO