使用csv.writer将®写入csv

时间:2014-05-14 09:44:58

标签: python csv unicode utf-8

我正在尝试将带有'®'的字符串写入csv文件:

csvfile  = open(destination, "wb")
csv_writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL, delimiter='\t')
for row in data:
    csv_writer.writerow(row)

csvfile.close()

和行看起来像这样:

[123, "str", "str2 ®"]

我试图写入csv的字符串是从xml中检索的,我认为它被编码为utf-8。

我收到错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/ec2-user/django/app/models.py", line 94, in import_data
    load_to_csv(out, out_data)
  File "/home/ec2-user/django/utils/util.py", line 90, in load_to_csv
    csv_writer.writerow(row)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 66: ordinal not in range(128)

然后我尝试将字符串编码为utf-8:

csvfile  = open(destination, "wb")
csv_writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL, delimiter='\t')
for row in data:
    for i, r in enumerate(row):
        if type(r) is str:
            row[i] = r.encode('utf-8')
    csv_writer.writerow(row)

csvfile.close()

但我仍然得到同样的错误..有人可以帮忙吗?已经卡住了一段时间..

1 个答案:

答案 0 :(得分:2)

您有 Unicode 值,而不是字节字符串。编码:

for row in data:
    row = [c.encode('utf8') if isinstance(c, unicode) else c for c in row]:
    csv_writer.writerow(row)