"utf-8-sig" 是否适合解码 UTF-8 和 UTF-8 BOM?

Is "utf-8-sig" suitable for decoding both UTF-8 and UTF-8 BOM?

我正在使用 Python CSV 库读取两个 CSV 文件。

一个是UTF-8-BOM编码的,另一个是UTF-8编码的。在我的实践中,我发现这两个文件都可以使用“utf-8-sig”作为编码类型来读取:

from csv import reader 
with open(file_path, encoding='utf-8-sig') as csv_file:
    c_reader = reader(csv_file, delimiter=',')
    headers = next(c_reader)    
    for row in c_reader:
        print(row)

我想确认一下,“utf-8-sig”是否适合解码 UTF-8 和 UTF-8 BOM? 我正在使用 Python 版本 3.6 和 3.7。感谢您的回答!

utf-8-sig 编解码器将解码 utf-8-sig-encoded 文本和使用标准 utf-8 编码

编码的文本
>>> s = 'Straße'
>>> utf8_sig = s.encode('utf-8-sig')
>>> utf8 = s.encode('utf')
>>> print(utf8_sig.decode('utf-8-sig'))
Straße
>>> print(utf8.decode('utf-8-sig'))
Straße

来自编解码器 docs:

Before any of the Unicode characters is written to the file, a UTF-8 encoded BOM (which looks like this as a byte sequence: 0xef, 0xbb, 0xbf) is written ... On decoding utf-8-sig will skip those three bytes if they appear as the first three bytes in the file.

Windows 环境中最常见的 utf-8-sig 编码。如果您在 mac 或 *nix 系统上与用户共享文件,他们希望收到标准的 utf-8 编码。