1

我的代码如下:

with open('C:\\Users\\...\\Documents\\RP_test_8.txt', 'w') as f:
    cf = csv.DictWriter(f, column_headers, extrasaction='ignore') 
    cf.writeheader()
    cf.writerows(r.data for r in records)

给了我一个 unicode 编码异常:

UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-141-410d45c40cce> in <module>()
      2     cf = csv.DictWriter(f, column_headers, extrasaction='ignore')
      3     cf.writeheader()
----> 4     cf.writerows(r.data for r in records)

C:\Users\...\AppData\Local\Continuum\anaconda2\lib\csv.pyc in writerows(self, rowdicts)
    156         for rowdict in rowdicts:
    157             rows.append(self._dict_to_list(rowdict))
--> 158         return self.writer.writerows(rows)
    159 
    160 # Guard Sniffer's type checking against builds that exclude complex()

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 30: ordinal not in range(128)

处理这个问题的最佳方法是什么?

4

1 回答 1

0

您可以按如下方式对字典中的每个值进行编码,然后将最终的字典列表发送到writerows函数。如果需要,您还可以对密钥进行编码。

import csv
cf = csv.DictWriter(f, column_headers, extrasaction='ignore')
cf.writeheader()
final_dict_list = []
for r in records:
    for d in r.data:
        final_dict_list.append({k:v.encode('utf8') for k,v in d.items()})
cf.writerows(final_dict_list)
于 2018-07-05T05:35:04.990 回答