无法读取 UTF-8 BOM \xef\xbb\xbf



读取以xefxbbxbf开头的文件时无法绕过此错误

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 63675320: invalid continuation byte

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'xefxbbxbf***后面跟着文件的其余部分。

我也试着用rb, re.sub xefxbbxbf打开它,但还没有成功。文件大小为65 mb,当读取'rb'并打印到一个新文件时,该文件只有一行,打开/工作速度很慢。

我在网上找到的每个答案都说使用utf-8-sig, utf-8或不使用。我正在使用python 3.9.6,无法得到这些建议的工作。

文件不符合UTF-8。它可能包含错误。可以是不同的编码。

错误可能是由于写入不完整,随后写入包含BOM。

选项1:替换错误

无效的UTF-8字符将替换为uFFFD

openitx = open(openit0, mode='r', errors='replace')

选项2:解析为二进制

你可以以二进制模式打开文件,它会给你原始字节而不是字符串。

openitx = open(openit0, mode='rb')

如果你是逐行读取文件,或者用正则表达式扫描它,其中一些东西仍然可以工作…您需要使用二进制正则表达式,但是(将b前缀添加到用于正则表达式的字符串,例如使用b'^#.*'而不是'^#.*')。

无论如何,您可能必须在解析后解码字节,但是以字节形式解析可能使您更容易弄清楚如何处理错误,并且它将保留无效数据以供稍后处理。

最新更新