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

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

最佳答案

您可以通过简单地在字符串前添加 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/

相关文章:

python - 在 Python 2 中,viewvalues()/viewitems() 相对于 itervalues()/iteritems() 的性能权衡是什么?

Python zipfile 不释放 zip 文件

Python Pandas 名称错误 : StringIO is not defined

python - StringIO 中的就地替换

Python:如何使用切片扩展列表?

python - 使用sklearn线性回归,如何限制计算的回归系数大于0?

python - 电子邮件的正则表达式也适用于十进制值。我如何解决它?

python - 如何在 Django 模板中添加注释?

django - 谁生成django欢迎页面的默认页面?

python - tempfile.TemporaryFile 与 StringIO