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.
Code
# 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: TrueHow 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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.