【问题标题】:CSV: when unicode is not unicode?CSV:当 unicode 不是 unicode 时?
【发布时间】:2019-12-02 01:11:04
【问题描述】:

为什么writerow() 说我在通过str,而我在通过unicode

import io
import csv

with io.open('test.csv', 'w', encoding="utf-8") as f:
    writer = csv.writer(f)
    x = [unicode(v, 'utf8') for v in ['id:ID', 'pos:string', 'definition:string', ':LABEL']]
    print x
    print type(x[0])
    writer.writerow(x)

[u'id:ID', u'pos:string', u'definition:string', u':LABEL']
<type 'unicode'>
Traceback (most recent call last):
 File "testcsv.py", line 9, in <module>
     writer.writerow(x)
  TypeError: write() argument 1 must be unicode, not str

【问题讨论】:

  • 我认为 Python 2.x 中的 csv 模块无法处理 Unicode。请参阅documentation 中的备注
  • 我同意这令人困惑——我认为正在发生以下情况:writer.writerow() 调用将x[0] 强制转换为str 并将其传递给f.write()(您使用io.open 打开的流) .回溯并没有清楚地表明这一点。
  • Python 处理文本,尤其是 CSV 文件,是 Python 3 中真正得到修复的一件事。您应该真正考虑改用 Python 3。

标签: python csv unicode python-2.x


【解决方案1】:

python 2 中的csv 模块不处理unicode。 python 2 文档gives an example 介绍了如何创建自己的 unicode csv 处理程序。

更好的选择是安装 backports.csv 模块,它允许您的 python 2 代码使用更新的 python 3 csv api,它处理 unicode。

使用pip install backports.csv 安装库后,此代码可在python 2 中运行:

>>> import io
>>> from backports import csv
>>> with io.open('test.csv', 'w', encoding="utf-8") as f:
>>>     writer = csv.writer(f)
>>>     x = [unicode(v, 'utf8') for v in ['id:ID', 'pos:string', 'definition:string', ':LABEL']]
>>>     print x
>>>     print type(x[0])
>>>     writer.writerow(x)
[u'id:ID', u'pos:string', u'definition:string', u':LABEL']
<type 'unicode'>

>>> with io.open('test.csv', encoding="utf-8") as f:
>>>     print f.read()
id:ID,pos:string,definition:string,:LABEL

【讨论】:

  • 当然,更好的选择是完全使用 Python 3。
猜你喜欢
  • 2013-07-05
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 2021-04-14
  • 2016-12-30
  • 1970-01-01
  • 2015-11-11
  • 1970-01-01
相关资源
最近更新 更多