Python 3 CSV文件给出UnicodeDecodeError:'utf-8'编解码器在打印时无法解码字节错误

HLH*_*HLH 25 python csv encoding utf-8 python-3.x

我在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))
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,它给了我这个错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 7386: invalid start byte
Run Code Online (Sandbox Code Playgroud)

我查看了csv文件,事实证明,如果我拿出一个ñ(顶部有一个波浪号的小n),每行打印都很好.

我的问题是,我已经查看了一系列针对类似问题的不同解决方案,但我仍然不知道如何解决这个问题,解码/编码等等.简单地取出数据中的ñ字符不是一个选项.

unu*_*tbu 49

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

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 7386: invalid start byte
Run Code Online (Sandbox Code Playgroud)

现在我们可以编写一个小脚本来查找是否有任何编码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))
Run Code Online (Sandbox Code Playgroud)

产量

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 ñ
Run Code Online (Sandbox Code Playgroud)

因此,尝试改变

with open('my_file.csv', 'r', newline='') as csvfile:
Run Code Online (Sandbox Code Playgroud)

对其中一种编码,例如:

with open('my_file.csv', 'r', encoding='mac_roman', newline='') as csvfile:
Run Code Online (Sandbox Code Playgroud)

  • 它对我有用,但是为什么用mac_roman而不是utf-8作为编码? (2认同)

小智 17

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


She*_*age 9

我也遇到了 python 3 的问题,并且使用编码类型为utf-16解决了我的问题

with open('data.csv', newline='',encoding='utf-16') as csvfile:
Run Code Online (Sandbox Code Playgroud)


Tim*_*inn 7

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

如果您尝试使用打开一个utf-16编码的文档open(... encoding='utf-8'),则会收到错误消息:

UnicodeDecodeError:“ utf-8”编解码器无法解码位置0的字节0xff:无效的起始字节

要解决此问题,请指定“ utf-16”编码或更改csv的编码。