【发布时间】:2012-10-18 16:17:36
【问题描述】:
我尝试将 Python 3 程序反向移植到 2.7,但遇到了一个奇怪的问题:
>>> import io
>>> import csv
>>> output = io.StringIO()
>>> output.write("Hello!") # Fail: io.StringIO expects Unicode
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unicode argument expected, got 'str'
>>> output.write(u"Hello!") # This works as expected.
6L
>>> writer = csv.writer(output) # Now let's try this with the csv module:
>>> csvdata = [u"Hello", u"Goodbye"] # Look ma, all Unicode! (?)
>>> writer.writerow(csvdata) # Sadly, no.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unicode argument expected, got 'str'
根据文档,io.StringIO() 返回 Unicode 文本的内存流。当我尝试手动为其提供 Unicode 字符串时,它可以正常工作。为什么它与csv 模块一起失败,即使正在写入的所有字符串都是Unicode 字符串?导致异常的str 来自哪里?
(我知道我可以改用StringIO.StringIO(),但我想知道在这种情况下io.StringIO() 有什么问题)
【问题讨论】:
-
我怀疑
from __future__ import unicode_literals在从使用“字节串文字”的 stdlib 模块子类化时可能会在 python2 中导致此问题
标签: python csv unicode python-2.7