在 Python 中检测字节顺序标记 (BOM)

问题描述

我找到了很多描述如何解析/忽略 BOM 的帖子,但找不到任何关于如何简单地输出一个文件是否包含 BOM 的真/假的信息。任何人都可以指出我在 Python 中执行此操作的正确方向吗?

解决方法

简单的答案是:读取前 4 个字节并查看它们。

with open("utf32le.file","rb") as file:
    beginning = file.read(4)
    # The order of these if-statements is important
    # otherwise UTF32 LE may be detected as UTF16 LE as well
    if beginning == b'\x00\x00\xfe\xff':
        print("UTF-32 BE")
    elif beginning == b'\xff\xfe\x00\x00':
        print("UTF-32 LE")
    elif beginning[0:3] == b'\xef\xbb\xbf':
        print("UTF-8")
    elif beginning[0:2] == b'\xff\xfe':
        print("UTF-16 LE")
    elif beginning[0:2] == b'\xfe\xff':
        print("UTF-16 BE")
    else:
        print("Unknown or no BOM")

不那么简单的答案是:

可能有些二进制文件似乎有 BOM,但它们可能仍然只是二进制文件,其中的数据意外地看起来像 BOM。

除此之外,您通常也可以将没有 BOM 的文本文件视为 UTF-8。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...