这是我的代码,

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

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


当前回答

这是一个在Python 3中转换CSV文件的例子:

try:
    inputReader = csv.reader(open(argv[1], encoding='ISO-8859-1'), delimiter=',',quotechar='"')
except IOError:
    pass

其他回答

如此:

open('filename', encoding='latin-1')

Or:

open('filename', encoding="ISO-8859-1")

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

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

我的问题类似于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   Ç

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

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

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

import pandas as pd

pd.read_csv('top50.csv', encoding='ISO-8859-1')

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

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

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