【问题标题】:Can't read UTF-8 BOM \xef\xbb\xbf无法读取 UTF-8 BOM \xef\xbb\xbf
【发布时间】: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 的坏字节让我觉得它只是写错了。您需要修复文件,而不是代码。
  • 我从来没有想过文件本身是错误的,谢谢你们的意见。我很感激

标签: python character-encoding


【解决方案1】:

文件不是有效的 UTF-8。 它可能包含错误。可能是不同的编码。

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

选项 1:替换错误

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

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

选项 2:解析为二进制

您可以以二进制模式打开文件,这会为您提供原始字节而不是字符串。

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

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

无论如何,您可能必须在解析后对字节进行解码,但解析为字节可能会让您更容易弄清楚如何处理错误,并且它将保留无效数据以供以后处理。

【讨论】:

  • 非常感谢您的意见!我尝试了errors=replace并得到了UnicodeEncodeError: 'charmap' codec can't encode character '\ufeff' in position 0: character maps to
  • utf-8-sig errors=replace 给了我这个错误;无法编码字符'\u0650'
  • 我没有尝试 rb 与我正在尝试做的正则表达式,我会尝试下一个。谢谢!
  • @Cogu:如果您收到“无法编码字符”,那么您的问题出在 代码的不同部分。当您打开文件进行阅读时,它解码字符但不编码它们。
猜你喜欢
  • 2018-10-12
  • 2013-01-06
  • 2016-03-22
  • 2013-09-10
  • 2011-06-21
  • 2019-03-24
  • 2011-07-21
  • 2014-03-04
  • 2018-07-30
相关资源
最近更新 更多