这是我的代码,

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

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


当前回答

我一直遇到这个错误,通常解决方案不是通过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

其他回答

试着用Pandas来阅读:

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

我的问题类似于UTF-8文本被传递给Python脚本。

在我的例子中,它来自SQL Server机器学习服务中使用sp_execute_external_script的SQL。不管出于什么原因,VARCHAR数据似乎被作为UTF-8传递,而NVARCHAR数据被作为UTF-16传递。

由于无法在Python中指定默认编码,并且没有用户可编辑的Python语句解析数据,所以我不得不在@input_data参数中的SELECT查询中使用SQL CONVERT()函数。

当这个查询

EXEC sp_execute_external_script @language = N'Python', 
@script = N'
OutputDataSet = InputDataSet
', 
@input_data_1 = N'SELECT id, text FROM the_error;'
WITH RESULT SETS (([id] int, [text] nvarchar(max)));

给出错误

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 0: unexpected end of data

使用CONVERT(类型,数据)(CAST(数据AS类型)也可以)

EXEC sp_execute_external_script @language = N'Python', 
@script = N'
OutputDataSet = InputDataSet
', 
@input_data_1 = N'SELECT id, CONVERT(NVARCHAR(max), text) FROM the_error;'
WITH RESULT SETS (([id] INT, [text] NVARCHAR(max)));

返回

id  text
1   Ç

下面的方法对我也有用。ISO 8859-1将节省很多,主要是如果使用语音识别api。

例子:

file = open('../Resources/' + filename, 'r', encoding="ISO-8859-1")

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

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

编码替换为encoding='ISO-8859-1'

For line in open('u。项”,编码= ' iso - 8859 - 1”):

print (line)