这是我的代码,

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')

其他回答

基于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

你可以用以下方法来解决这个问题:

for line in open(your_file_path, 'rb'):

'rb'以二进制模式读取文件。点击这里阅读更多。

“utf-8”编解码器无法解码位置7044中的0xed字节:无效的延续字节

上述错误是由于编码造成的

解决方案:-使用" encoding='latin-1' "

参考:https://pandas.pydata.org/docs/search.html?q=encoding

如果你使用的是python2,下面是解决方案:

import io
for line in io.open("u.item", encoding="ISO-8859-1"):
    # Do something

因为encoding参数对open()不起作用,你将得到以下错误:

'encoding'是此函数的无效关键字参数