这是我的代码,

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

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


当前回答

有时当使用open(filepath),其中filepath实际上不是一个文件时,会得到相同的错误,所以首先要确保你要打开的文件存在:

import os
assert os.path.isfile(filepath)

其他回答

有时当使用open(filepath),其中filepath实际上不是一个文件时,会得到相同的错误,所以首先要确保你要打开的文件存在:

import os
assert os.path.isfile(filepath)

我正在使用从Kaggle下载的数据集,同时读取这个数据集,它抛出了这个错误:

UnicodeDecodeError: 'utf-8'编解码器不能解码字节0xf1在位置 183:无效的延续字节

这就是我解决问题的方法。

import pandas as pd

pd.read_csv('top50.csv', 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])))

试着用Pandas来阅读:

pd.read_csv('u.item', sep='|', names=m_cols, encoding='latin-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