“for line in...”导致 UnicodeDecodeError: 'utf-8' 编解码器无法解码字节
- 2025-01-06 08:32:00
- admin 原创
- 108
问题描述:
这是我的代码,
for line in open('u.item'):
# Read each line
每当我运行此代码时,都会出现以下错误:
UnicodeDecodeError:'utf-8'编解码器无法解码位置 2892 中的字节 0xe9:无效的连续字节
我尝试解决这个问题,并在 open() 中添加一个额外的参数。代码如下:
for line in open('u.item', encoding='utf-8'):
# Read each line
但又出现了同样的错误。那我该怎么办?
解决方案 1:
根据Mark Ransom 的建议,我找到了该问题的正确编码。编码是"ISO-8859-1"
,因此替换open("u.item", encoding="utf-8")
为open('u.item', encoding = "ISO-8859-1")
将解决问题。
解决方案 2:
以下方法对我也有用。ISO 8859-1将节省很多,主要是在使用语音识别 API 时。
例子:
file = open('../Resources/' + filename, 'r', encoding="ISO-8859-1")
解决方案 3:
您的文件实际上并不包含 UTF-8 编码数据;它包含其他编码。找出该编码并在调用中使用它open
。
例如,在 Windows-1252 编码中,0xe9
将是字符é
。
解决方案 4:
尝试使用Pandas进行读取:
pd.read_csv('u.item', sep='|', names=m_cols, encoding='latin-1')
解决方案 5:
这有效:
open('filename', encoding='latin-1')
或者:
open('filename', encoding="ISO-8859-1")
解决方案 6:
如果您使用的是 Python 2,则解决方案如下:
import io
for line in io.open("u.item", encoding="ISO-8859-1"):
# Do something
由于该encoding
参数不适用于open()
,您将收到以下错误:
TypeError:'encoding' 是此函数的无效关键字参数
解决方案 7:
您可以使用以下方法解决该问题:
for line in open(your_file_path, 'rb'):
'rb' 以二进制模式读取文件。点击此处了解更多信息。
解决方案 8:
我正在使用从Kaggle下载的数据集,在读取此数据集时引发此错误:
UnicodeDecodeError:'utf-8'编解码器无法解码位置183中的字节0xf1:无效的连续字节
这就是我修复它的方法。
import pandas as pd
pd.read_csv('top50.csv', encoding='ISO-8859-1')
解决方案 9:
你可以尝试这个方法:
open('u.item', encoding='utf8', errors='ignore')
解决方案 10:
根据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('
', '')
# 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])))
解决方案 11:
这是在 Python 3 中转换 CSV 文件的示例:
try:
inputReader = csv.reader(open(argv[1], encoding='ISO-8859-1'), delimiter=',',quotechar='"')
except IOError:
pass
解决方案 12:
UnicodeDecodeError:'utf-8'编解码器无法解码位置7044中的字节0xed:无效的连续字节
上述错误是由于编码引起的
解决方案:- 使用“encoding='latin-1'”
参考:-https://pandas.pydata.org/docs/search.html?q=encoding
解决方案 13:
编码替换为encoding='ISO-8859-1'
for line in open('u.item', encoding='ISO-8859-1'):
# print(line)
解决方案 14:
有时当使用open(filepath)
实际上filepath
不是文件时会出现相同的错误,因此首先确保您尝试打开的文件存在:
import os
assert os.path.isfile(filepath)
解决方案 15:
使用Notepad++打开您的文件,选择“编码”或“Encodage”菜单来识别或从 ANSI 转换为 UTF-8 或ISO 8859-1代码页。
解决方案 16:
为了使网页能够更快地搜索到 google 请求的类似问题(关于 UTF-8 错误),我在这里留下我的解决方案以供其他人参考。
我在打开 .csv 文件时遇到了以下问题:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 150: invalid continuation byte
我用记事本打开了文件,数了数第 150 个位置:那是一个西里尔符号。我用“另存为...”命令重新保存了该文件,编码为“UTF-8”,我的程序开始工作了。
解决方案 17:
我不断遇到此错误,并且通常解决方案无法解决,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
解决方案 18:
如果您直接从 github 或 kaggle 加载数据,请使用此项 DF=pd.read_csv(file,encoding='ISO-8859-1')
解决方案 19:
就我而言,出现此问题是因为我将 excel 文件 (.xlsx) 的扩展名直接修改为 (.csv) 文件...
解决方案是打开文件,然后将其保存为新的(.csv)文件(即文件->另存为->选择(.csv)扩展名并保存。这对我有用。
解决方案 20:
我的问题类似,UTF-8 文本被传递给 Python 脚本。
就我而言,它是使用 SQL Server 机器学习服务中的 sp_execute_external_script 从 SQL 中获取的。无论出于何种原因,VARCHAR 数据似乎以 UTF-8 传递,而 NVARCHAR 数据则以 UTF-16 传递。
由于无法在 Python 中指定默认编码,并且没有用户可编辑的 Python 语句来解析数据,因此我不得不CONVERT()
在参数中的 SELECT 查询中使用 SQL 函数@input_data
。
因此,虽然这个查询
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(type, data)
(CAST(data AS type)
也可以)
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 Ç
解决方案 21:
只需打开 csv 文件并另存为“CSV UTF-8(逗号分隔)(*.csv)”。您会在另存为文件选项列表中找到它。
保存并关闭文件后,导入数据
数据 = pd.read_csv('文件名.csv')