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

Ami*_*mit 24 python stringio python-2.7

尝试使用以下字符串作为文件读取以下字符串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
Run Code Online (Sandbox Code Playgroud)

πόδ*_*κύς 33

您可以通过在字符串之前添加au来使字符串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
""")
Run Code Online (Sandbox Code Playgroud)

您的初始值应为unicode.

  • @JustinBarber - 如果数据字符串已经设置为变量并且你必须以`StringIO()`开头怎么办?`的unicode(可变)`.回答了我自己的问题.谢谢. (4认同)

jtl*_*lz2 8

宁可使用(为我解决此确切问题):

from StringIO import StringIO
Run Code Online (Sandbox Code Playgroud)

  • 对于 Python3,我不能使用“来自 StringIO”。在我的情况下,'from io import BytesIO' 正在工作 (2认同)