尝试使用 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
最佳答案
您可以通过简单地在字符串前添加 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 .
关于python - 如何在 Python 2.7 中使用 StringIO 解决 TypeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22316333/