如何在Python 2.7中使用StringIO解决TypeError? [英] How can I resolve TypeError with StringIO in Python 2.7?
本文介绍了如何在Python 2.7中使用StringIO解决TypeError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试使用StringIO
将以下字符串读取为文件,但出现以下错误.我该如何解决?
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
推荐答案
您可以通过在字符串之前添加一个u以使字符串成为unicode来解决错误:
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
""")
您的初始值应为Unicode .
这篇关于如何在Python 2.7中使用StringIO解决TypeError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文