首页 > 解决方案 > 写入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

标签: pythonpython-3.x

解决方案


您需要检查 Windows 中的输入文件编码是什么,并在输入文件打开语句中使用 encoding='' 。在 Windows 中,默认结尾不是“utf8”,因此如果未使用正确的编码打开,如下所示,将会出现编码问题,

open(input_file_name,encoding='iso-8859-1')

或者更好地将您的输入文件更改为“utf8”编码,以便在windoes 和linux 上无需修改即可使用该脚本。


推荐阅读