CSV读取引发“UnicodeDecodeError:'charmap' codec无法解码...”错误。

4
我已经阅读了所有我能找到的文章,但是我的情况看起来很特殊。因为我对Python完全不熟悉,所以可能是基础问题。我遇到了下面的错误:
UnicodeDecodeError: 'charmap'编解码器无法将第70位上的0x8d字节解码:字符映射到未定义的位置
当我运行代码时,就会出现这个错误。
import csv

input_file = 'input.csv'
output_file = 'output.csv'
cols_to_remove = [4, 6, 8, 9, 10, 11,13, 14, 19, 20, 21, 22, 23, 24]

cols_to_remove = sorted(cols_to_remove, reverse=True)
row_count = 0 # Current amount of rows processed

with open(input_file, "r") as source:
    reader = csv.reader(source)
    with open(output_file, "w", newline='') as result:
        writer = csv.writer(result)
        for row in reader:
            row_count += 1
            print('\r{0}'.format(row_count), end='')
            for col_index in cols_to_remove:
                del row[col_index]
            writer.writerow(row)

我做错了什么?


你使用的是哪个Python版本? - shubhambharti201
@shubhambharti201 3.7 - Momboosa
这是一个解码错误,您可以在这里找到帮助。 - Shijith
你应该检查第70个位置的字符,并找到该字符的编码格式。然后相应地对文件进行编码。 - Shahir Ansari
3个回答

6
在Python 3中,csv模块会将文件处理成unicode字符串,因此需要先解码输入文件。如果你知道确切的编码方式,可以使用该编码方式;或者只需使用Latin1,因为它将每个字节映射到具有相同代码点的unicode字符,因此解码和编码保持字节值不变。下面是可能的代码示例:
...
with open(input_file, "r", encoding='Latin1') as source:
    reader = csv.reader(source)
    with open(output_file, "w", newline='', encoding='Latin1') as result:
        ...

这似乎至少已经成功通过了错误。还有700万行需要处理,所以看到输出结果将会很有趣。我确认了编码是UTF-8,但是像其他人建议的添加encoding="utf8"却导致了另一个解码错误。 - Momboosa

4
在打开文件时加上encoding="utf8"。请尝试使用以下代码:
with open(input_file, "r", encoding="utf8") as source:
    reader = csv.reader(source)
    with open(output_file, "w", newline='', encoding="utf8") as result:

1
UTF-8通常是Python 3中的默认编码方式。如果默认编码出现错误,那么它使用UTF-8也很可能出错。 - Serge Ballesta
@SergeBallesta 有什么想法,为什么它默认使用 charmap 进行解码?我没有看到他/她在打开文件时指定编码,所以我也期望它是 UTF-8。 - emremrah

0
  1. 尝试使用 pandas

input_file = pandas.read_csv('input.csv') output_file = pandas.read_csv('output.csv')

  1. 尝试将文件另存为 CSV UTF-8 格式

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接