如何解决Python 2.7中StringIO的TypeError?
我想用 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 个回答
14
不如使用这个方法(这个方法正好解决了我的问题):
from StringIO import StringIO
42
你可以通过在你的字符串前面加一个“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
""")
你的初始值 应该是unicode格式。