Python 3 CSV文件给出UnicodeDecodeError:“utf-8”编码解码器无法解码字节错误

2024-06-06 21:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python 3中有以下代码,它用于打印csv文件中的每一行。

import csv
with open('my_file.csv', 'r', newline='') as csvfile:
    lines = csv.reader(csvfile, delimiter = ',', quotechar = '|')
    for line in lines:
        print(' '.join(line))

但当我运行它时,它会给我一个错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 7386: invalid start byte

我浏览了csv文件,结果发现如果我取出一个n I n(上面有一个平铺的小n),每一行都可以打印出来。

我的问题是,对于类似的问题,我已经研究了很多不同的解决方案,但是我仍然不知道如何解决这个问题,解码/编码什么,等等。简单地去掉数据中的字符不是一个选择。


Tags: 文件csvcsvfile代码inimportmyas
3条回答

with open('my_file.csv', 'r', newline='', encoding='ISO-8859-1') as csvfile:

UTC-8编码中没有列出字符。要解决此问题,您可以改用ISO-8859-1编码。有关此编码的详细信息,请参阅下面的链接: https://www.ic.unicamp.br/~stolfi/EXPORT/www/ISO-8859-1-Encoding.html

我们知道文件包含字节b'\x96',因为它在错误消息中提到:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 7386: invalid start byte

现在,我们可以编写一个小脚本,以确定是否存在b'\x96'解码到ñ的任何编码:

import pkgutil
import encodings
import os

def all_encodings():
    modnames = set([modname for importer, modname, ispkg in pkgutil.walk_packages(
        path=[os.path.dirname(encodings.__file__)], prefix='')])
    aliases = set(encodings.aliases.aliases.values())
    return modnames.union(aliases)

text = b'\x96'
for enc in all_encodings():
    try:
        msg = text.decode(enc)
    except Exception:
        continue
    if msg == 'ñ':
        print('Decoding {t} with {enc} is {m}'.format(t=text, enc=enc, m=msg))

会产生

Decoding b'\x96' with mac_roman is ñ
Decoding b'\x96' with mac_farsi is ñ
Decoding b'\x96' with mac_croatian is ñ
Decoding b'\x96' with mac_arabic is ñ
Decoding b'\x96' with mac_romanian is ñ
Decoding b'\x96' with mac_iceland is ñ
Decoding b'\x96' with mac_turkish is ñ

因此,尝试改变

with open('my_file.csv', 'r', newline='') as csvfile:

其中一个编码,例如:

with open('my_file.csv', 'r', encoding='mac_roman', newline='') as csvfile:

对于遇到主题中显示的相同错误的其他人,请注意csv文件的文件编码。可能不是utf-8。我刚刚注意到,LibreOffice今天为我创建了一个utf-16编码的文件,但没有提示我,尽管我无法复制。

如果尝试使用open(... encoding='utf-8')打开utf-16编码的文档,将得到错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

若要修复,请指定“utf-16”编码或更改csv的编码。

相关问题 更多 >