utf-8-sig Adds And Strips The BOM

utf-8-sig writes the BOM on encode and consumes it on decode, while plain utf-8 leaves U+FEFF glued to the first CSV field after a round trip.

PythonData Integrity

Code

pythonsnippet
14 lines
# 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)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How it works

All data sits in top-level bindings: text, raw, decoded_plain, clean.

Points of care

  • The only thing required is the runtime; packages and installs stay out.

Using it

Look for the starts with BOM bytes:, plain decode leaks:, sig decode clean: prefixes when the file runs; they tie each line to its step.

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `text`, `raw`, `decoded_plain`.