python - "utf-8-sig"是否适契约(Contract)时解码 UTF-8 和 UTF-8 BOM?

标签 python csv utf-8 character-encoding

我正在使用 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”是否适契约(Contract)时解码 UTF-8 和 UTF-8 BOM?
我使用的是 Python 3.6 和 3.7 版。感谢您的回答!

最佳答案

utf-8-sig 编解码器将解码 utf-8-sig 编码的文本和使用标准 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 编码是他们期望收到的。

关于python - "utf-8-sig"是否适契约(Contract)时解码 UTF-8 和 UTF-8 BOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63508421/

相关文章:

python - 在python中发送utf-8地址到urlretrieve

postgresql - 识别隐藏的非 UTF8 编码字符

php - 如何使用 PHP 删除字符串中所有出现的 c2a0?

python - <a></a> 标签放在引号中时不会呈现

python - 如何在 Python 中以相反的顺序读取 CSV 文件?

python - 如何将计算应用于文本文件的列?

r - 使用 vroom 在 R 中部分读取非常大的 csv.gz

python - Pyqt5:QtableWidgetItem "None"

python - 错误: command 'clang' failed with exit status 1 on pip install TA-Lib

python - 表单发送错误,Flask