我想使用python的3模块写入csv。但是,我没有找到任何文档可以告诉我如何传递编码参数。
我的代码:
for item in list_documents:
print("The item is: ", item)
wb = openpyxl.load_workbook(path+item)
sh = wb.get_active_sheet()
split_item = item.split(".")[0]
new_name = str(split_item) + ".csv"
with open(path + new_name, 'w', newline="") as f:
c = csv.writer(f, delimiter=";")
counter = 0
for r in sh.rows:
counter += 1
print(counter)
c.writerow([cell.value for cell in r])
我的代码从xlsx文件读取行并将其放入csv。对于csv.writer
,我似乎无法指定我想要UTF-8编码。
错误消息:
Traceback (most recent call last):
File "C:/Users/aprofir/Desktop/python_project/transform_data/xlsx_to_csv.py", line 31, in <module>
c.writerow([cell.value for cell in r])
File "C:\Users\aprofir\AppData\Local\Programs\Python\Python37-32\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u0142' in position 173: character maps to <undefined>
据我了解,字符\u0142
表示波兰字母ł。我有办法解决这个问题吗?我无法删除或更改数据。
答案 0 :(得分:1)
您可以在此处打开文件时指定编码:
with open(path + new_name, 'w', newline="", encoding='utf-8') as f: