【问题标题】:How to specify encoding type for csv.writer? [duplicate]如何为 csv.writer 指定编码类型? [复制]
【发布时间】:2019-10-04 03:49:48
【问题描述】:

我想使用 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 指的是波兰字母ł。有没有办法解决这个问题。我无法删除或更改数据。

【问题讨论】:

  • 试过with 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)...) 而不是使用加号运算符连接文件名

标签: python python-3.x csv encoding


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-27
    • 2015-05-20
    • 2023-04-02
    • 1970-01-01
    • 2018-01-28
    • 2018-07-20
    • 2012-03-30
    • 2022-11-18
    相关资源
    最近更新 更多