[英]codecs issue when writing to csv python3
output_file = open(OUTPUT_FILENAME,'w',newline='') #create new file
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
#some logic
for row in items:
#di dictionary
dict_writer.writerow(di)
您好,我是 python 的新手。 我在 Linux (centos) 上创建了这个脚本我运行它并且它工作正常,我尝试在 windows 上运行它我得到了这个错误
Traceback (most recent call last):
File "C:\Users\user157\Desktop\test.py", line 180, in <module>
dict_writer.writerow(di)
File "C:\Users\user157\AppData\Local\Programs\Python\Python38-32\lib\csv.py", line 154, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\Users\user157\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1256.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\xe3' in position 33: character maps to <undefined>
我在写字典之前尝试通过使用来解决它,但仍然是同样的错误
for k,v in di.items():
try:
di[k] =v.encode().decode('utf-8')
except:
pass
我在 centos 上有 python 3.7.5,在 windows 上有 3.8.2
您需要检查 Windows 中的输入文件编码是什么,并在输入文件打开语句中使用 encoding='' 。 在 windows 中,默认结尾不是“utf8”,因此如果未使用正确的编码打开,如下所示,
open(input_file_name,encoding='iso-8859-1')
或者更好地将您的输入文件更改为“utf8”编码,这样脚本就可以在windoes和linux中使用而无需修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.