← 中文资源

简体中文版本

utf-8-sig 写入并吃掉 BOM

utf-8-sig 编码写入 BOM、解码自动吃掉;用普通 utf-8 解码会把 U+FEFF 粘在首字段前,Excel 导出的 CSV 解析常栽在这里。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

starts with BOM bytes: True
plain decode leaks: '\ufeffsku'
sig decode clean: True
roundtrip: True

实现说明

演示用的数据放在这几个模块级绑定中:text、raw、decoded_plain、clean。

使用要点

  • 直接运行文件,输出会带上标签,比如 starts with BOM bytes:、plain decode leaks:、sig decode clean:——输出的每一行都能指回产生它的那次调用。

常见问题

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件用顶层绑定保存自己的状态:text、raw、decoded_plain。

代码示例

# utf-8-sig 编码会在开头写入 BOM(U+FEFF 的字节序列)
text = "sku,qty\nSKU-1,3"
raw = text.encode("utf-8-sig")
print("starts with BOM bytes:", raw[:3] == b"\xef\xbb\xbf")

# 用 utf-8 解码不做 BOM 处理:首字段前面粘着 \ufeff
decoded_plain = raw.decode("utf-8")
print("plain decode leaks:", repr(decoded_plain.split(",")[0]))

# 用 utf-8-sig 解码则把它吃掉,回到干净文本
clean = raw.decode("utf-8-sig")
print("sig decode clean:", clean == text)

print("roundtrip:", raw.decode("utf-8-sig").encode("utf-8-sig") == raw)