写入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

评论