这是我的代码,

for line in open('u.item'):
# Read each line

每当我运行这段代码,它给出以下错误:

UnicodeDecodeError: 'utf-8' codec无法解码字节0xe9在位置2892:无效的延续字节

我试图解决这个问题,并在open()中添加了一个额外的参数。代码如下:

for line in open('u.item', encoding='utf-8'):
# Read each line

但是它又给出了同样的错误。那我该怎么办呢?


当前回答

试着用Pandas来阅读:

pd.read_csv('u.item', sep='|', names=m_cols, encoding='latin-1')

其他回答

在我的情况下,这个问题发生,因为我修改了一个excel文件(.xlsx)的扩展名直接到(.csv)文件直接…

解决方案是打开文件,然后将其保存为新的(.csv)文件(即file -> save as ->选择(.csv)扩展名并保存它。这对我很管用。

您的文件实际上并不包含UTF-8编码的数据;它包含一些其他编码。弄清楚这种编码是什么,并在开放呼叫中使用它。

例如,在Windows-1252编码中,0xe9将是字符é。

根据Mark Ransom的建议,我找到了解决这个问题的正确编码。编码是“ISO-8859-1”,因此替换open(“u。Item ", encoding="utf-8")与open('u。item', encoding = "ISO-8859-1")将解决问题。

基于Stackoverflow上的另一个问题和本文之前的回答,我想添加一个帮助来找到正确的编码。

如果你的脚本运行在Linux操作系统上,你可以通过file命令获取编码:

file --mime-encoding <filename>

下面是一个python脚本来为你做这件事:

import sys
import subprocess

if len(sys.argv) < 2:
    print("Usage: {} <filename>".format(sys.argv[0]))
    sys.exit(1)

def find_encoding(fname):
    """Find the encoding of a file using file command
    """

    # find fullname of file command
    which_run = subprocess.run(['which', 'file'], stdout=subprocess.PIPE)
    if which_run.returncode != 0:
        print("Unable to find 'file' command ({})".format(which_run.returncode))
        return None

    file_cmd = which_run.stdout.decode().replace('\n', '')

    # run file command to get MIME encoding
    file_run = subprocess.run([file_cmd, '--mime-encoding', fname],
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    if file_run.returncode != 0:
        print(file_run.stderr.decode(), file=sys.stderr)

    # return  encoding name only
    return file_run.stdout.decode().split()[1]

# test
print("Encoding of {}: {}".format(sys.argv[1], find_encoding(sys.argv[1])))

我一直遇到这个错误,通常解决方案不是通过encoding='utf-8'解决的,而是实际上使用engine='python',就像这样:

import pandas as pd

file = "c:\\path\\to_my\\file.csv"
df = pd.read_csv(file, engine='python')
df

文档的链接在这里:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html