UnicodeEncodeError:'ascii'编解码器无法编写python写入csv中的字符

时间:2017-08-15 22:13:10

标签: python-3.x unicode ascii python-3.5 export-to-csv

当有特殊字符时,我的代码会生成异常。我该如何解决这个问题?我的代码:

with open((cmd_args.directory_path+"/"+collectn+"_"+dt.strftime(
        dt.today(), '%m-%d-%y_%H:%M:%S')+".psv"), 'w') as csvfile:


writer = csv.DictWriter(csvfile,delimiter=cmd_args.delimiter, fieldnames=fieldnames, extrasaction='ignore')
writer.writeheader()
for x in collection_filter_items:
    writer.writerow(x)
csvfile.close()

我收到以下异常:

    Traceback (most recent call last):
  File "./export.py", line 150, in <module>
    main(sys.argv[1:])
  File "./export.py", line 140, in main
    writer.writerow(x)
  File "/usr/lib/python3.5/csv.py", line 153, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
UnicodeEncodeError: 'ascii' codec can't encode character '\xae' in position 59: ordinal not in range(128)

0 个答案:

没有答案