Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何为csv.writer指定编码类型?_Python_Python 3.x_Csv_Encoding - Fatal编程技术网

Python 如何为csv.writer指定编码类型?

Python 如何为csv.writer指定编码类型?,python,python-3.x,csv,encoding,Python,Python 3.x,Csv,Encoding,我想使用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_ite

我想使用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编码

错误消息:

回溯(最近一次呼叫最后一次):
文件“C:/Users/aprofir/Desktop/python_project/transform_data/xlsx_to_csv.py”,第31行,在
c、 writerow([cell.value用于r中的单元格])
文件“C:\Users\aprofir\AppData\Local\Programs\Python\Python37-32\lib\encodings\cp1252.py”,第19行,在encode中
返回codecs.charmap\u encode(输入、自身错误、编码表)[0]
UnicodeEncodeError:“charmap”编解码器无法对173位置的字符“\u0142”进行编码:字符映射到

据我所知,字符
\u0142
指的是波兰语字母ł。我有办法解决这个问题吗。我无法删除或更改数据

您可以在此处打开文件时指定编码:

with open(path + new_name, 'w', newline="", encoding='utf-8') as f:

使用open(path+new_name,'w',newline=“”,encoding=“utf8”)尝试了
?如果您使用UTF-8作为编码并希望随后在Excel中打开CSV,请改用
encoding='UTF-8-sig'
;否则,Excel将假定CSV是ANSI编码的(一种本地化编码,在美国Windows上通常为
cp1252
)。我建议使用open(os.path.join(path,new_name)…)而不是将文件名与加号操作符连接起来