DictWriter无法在Python 3中处理unicode

时间:2018-06-20 13:47:49

标签: python-3.x csv dictionary unicode utf-8

我想将字典列表输出到CSV文件。

我有以下代码:

# -*- coding: utf-8 -*-
import csv

items = [{'ởne': 1, 'twở': 2}, {'ởne': 1, 'twở': 2}]
# Note the usage of the "ở" character, aka "\u1edf"

with open('output.csv', 'w') as f:
    fieldnames = items[0].keys() # fetching the keys of the first item as fieldnames
    w = csv.DictWriter(f, fieldnames=fieldnames, delimiter=';', lineterminator='\n')
    w.writeheader()
    w.writerows(items)

此操作失败,并显示以下错误:

  

UnicodeEncodeError:'charmap'编解码器无法在位置0编码字符'\ u1edf':字符映射到

如何使我的商品正确输出到CSV?

0 个答案:

没有答案