我正在使用 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/