【发布时间】:2021-08-09 17:37:43
【问题描述】:
尝试读取以 \xef\xbb\xbf 开头的文件时,我无法绕过此错误
UnicodeDecodeError:“utf-8”编解码器无法解码位置 63675320 中的字节 0xe4:无效的继续字节
openit = [any1file for any1file in os.listdir('.') if any1file.endswith('.Log')]
if len(openit) != 1:
raise ValueError('should be only one Log file in the current directory')
openit0 = openit[0]
到目前为止我已经尝试过(分别);
openitx = open(openit0, mode='r', encoding='utf-8-sig')
openitx = open(openit0, mode='r', encoding='utf-8')
openitx = open(openit0, mode='r', encoding='None')
openitx = open(openit0, mode='r', encoding=None)
openitx = open(openit0, mode='r', encoding='utf-16-le')
openitx = open(openit0, mode='r')
test = openitx.read()
openitx = Path('ncclog.Log', encoding='UTF-8').read_text()
openitx = Path('ncclog.Log', encoding='UTF-8-Sig').read_text()
with open(openit0, mode='r') as file: #Tried with utf-8, utf-8-sig, nothing
rfile = file.read()
当我使用“rb”打开时,我可以读取文件,但我不想那样打开它。
openitx = open(openit0, mode='rb')
openit1 = openitx.read()
输出看起来像
b'\xef\xbb\xbf*** 后跟文件的其余部分。
我也尝试过用 rb 打开它,re.sub xef\xbb\xbf 但还没有成功。 该文件为 65 mb,当读取“rb”并打印到新文件时,该文件全部为一行,打开/使用速度非常慢。
我在网上找到的每个答案都说使用 utf-8-sig、utf-8 或不使用。我正在使用 python 3.9.6 并且无法获得任何这些建议。
【问题讨论】:
-
鉴于该错误涉及位置 63675320 中的无效 utf8 代码,是什么让您认为这与字节顺序标记有关?
-
文件中有 63MB 的坏字节让我觉得它只是写错了。您需要修复文件,而不是代码。
-
我从来没有想过文件本身是错误的,谢谢你们的意见。我很感激