Excel adds a BOM to display Vietnamese correctly; a small Python parser plus golden tests can expose it and two other silent bugs.
Key takeaways
- The three BOM bytes 0xef 0xbb 0xbf pollute the first column name when decoding with plain utf-8; utf-8-sig skips them automatically.
- Python's csv module does not report malformed rows by default, and errors='replace' silently inserts replacement characters; both must be switched to strict mode.
- Golden tests save the parser's normalized output, so any change in encoding or delimiter handling shows up as a diff awaiting review.
With just three extra bytes at the start of a file
0xef 0xbb 0xbf
, the data pipeline can't find the "Customer ID" column. The code throws no exception; it just quietly produces a column name starting with invisible characters, and every lookup by that column name fails afterward.
Work as a Forward Deployed Engineer (FDE) long enough and you'll run into this sooner or later. The customer exports data from Excel, legacy finance software, or a third-party system and sends you a CSV file. Vietnamese text, or any language with diacritics, exposes three classic bugs: encoding, BOM, and delimiters.
This guide builds a small parser based on the Python standard library that handles all three problems at once, then locks in its behavior with golden tests. You only need Python 3 and pytest. The code is simplified for readability; add logging and error handling before using it in a real project.
Why do customer files often carry a BOM?
According to the Python documentation, the byte order mark (BOM) is the byte sequence
0xef 0xbb 0xbf
. It is a UTF-8 variant originating from Microsoft Notepad, and Python names the corresponding codec
utf-8-sig
. The BOM isn't added by the customer themselves; it's added by the software they use.
The culprit is Excel. In a 2014 article, Chase Seibert pointed out that Excel 2007, 2010, and 2013 only recognize UTF-8 when the file has a BOM.
Without a BOM, Vietnamese diacritics show up as garbled text, so export tools insert a BOM to make Excel display things correctly. The result: files that reach you often carry a BOM, while files without one often show mojibake when the customer opens them in Excel.
The same article points out another trap: if the file has both a BOM and a
sep=,
line at the top, Excel on Windows ignores the BOM. The article was written in 2014, so verify against the Excel version your customer actually uses. Even so, whenever you see a
sep=
line at the top of a file, this bug should be your first suspicion.
Step 1: Build a sample that resembles the customer's file
Start with a file containing all the tricky cases: a BOM, semicolon delimiters, and an address that wraps inside double quotes.
# make_fixture.py
from pathlib import Path
FIX = Path("tests/fixtures")
FIX.mkdir(parents=True, exist_ok=True)
text = ('Customer ID;Full name;Address\r\n'
'C01;Anna Wałęsa;"12 Ly Thuong Kiet Street\r\nWard 7"\r\n')
(FIX / "bom_semicolon.csv").write_bytes(text.encode("utf-8-sig"))Check: run
python -c "print(open('tests/fixtures/bom_semicolon.csv','rb').read(3))", and the output must be
b'\xef\xbb\xbf'
. For files in legacy encodings, don't invent samples yourself: ask the customer for a real file and anonymize it. The closer the sample is to real data, the more valuable the test.
Step 2: Read the bytes first, then determine the encoding
The most common mistake is opening the file with
encoding="utf-8"
and assuming everything is fine. With a file that has a BOM, the BOM character sticks to the beginning of the first column name. According to the Python documentation, if the file's first three bytes are a BOM, the
utf-8-sig
codec skips them; that's the direct fix.
If the file isn't valid UTF-8, Python also offers the
cp1258
codec for Vietnamese, namely windows-1258. Python's standard encoding table includes neither TCVN nor VISCII. If the customer uses one of those, you'll need a separate conversion tool.
# customer_csv.py
CANDIDATES = ("utf-8-sig", "cp1258")
def detect_encoding(raw: bytes) -> str:
for enc in CANDIDATES:
try:
raw.decode(enc, errors="strict")
return enc
except UnicodeDecodeError:
continue
raise ValueError("无法用任何已知编码解码该文件")The key is
errors="strict"
. According to the Python documentation, this is the default and raises an error on illegal bytes. By contrast,
errors="replace"
silently inserts the character U+FFFD at damaged spots. The parser runs as usual, but in the data written to the customer's system, letters with diacritics have turned into little boxes.
The order in which you try encodings matters too. UTF-8 is structurally strict, so files written in other encodings will very likely fail to decode with it.
Single-byte code pages like cp1258 are far more permissive: almost any byte sequence decodes, even if the result is gibberish. One line of code shows it: decode the UTF-8 bytes of a name as cp1258:
>>> "Wałęsa".encode("utf-8").decode("cp1258")
'Wałęsa'No exception, just a mangled name. So always try
utf-8-sig
first, and let the golden test in Step 5 catch any mistaken choice of cp1258.
Step 3: Open the file with newline=''
csv
The module documentation is explicit: if you don't specify
newline=''
, newlines embedded inside quoted fields won't be parsed correctly. An address that wraps from "12 Ly Thuong Kiet Street" to "Ward 7" is exactly this case. Without this argument, one customer could be split into two broken rows.
import csv
def parse_file(path, expected_cols: int) -> list[list[str]]:
raw = open(path, "rb").read()
enc = detect_encoding(raw)
with open(path, encoding=enc, errors="strict", newline="") as f:
sample = f.read(4096)
f.seek(0)
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
rows = list(csv.reader(f, dialect, strict=True))
check_columns(rows, expected_cols)
return rowsCheck: run
print(parse_file("tests/fixtures/bom_semicolon.csv", 3)), and you should get exactly two rows. The first cell must be
'Customer ID'
, with no
''
before it, and the address cell must contain a newline.
Step 4: Don't fully trust the Sniffer
csv.Sniffer
to infer the file's format. The documentation allows passing a
delimiters
argument to restrict which characters can serve as delimiters; here that's comma, semicolon, tab, and pipe. This prevents the Sniffer from picking some unrelated character in the data.
But the Sniffer still has weaknesses. According to the documentation, when
,
and
;
both split every row equally cleanly, the Sniffer chooses based on the priority order in the
preferred
property, regardless of how often each character appears.
Imagine a distributor's file where prices are written as "125,5" and the delimiter is a semicolon. If every row has the same number of price cells, the comma splits each row just as consistently as the semicolon, and the Sniffer may pick the wrong one.
So you need an independent check, based on information confirmed with the customer during requirements gathering: the column count.
def check_columns(rows, expected_cols):
for i, row in enumerate(rows):
if len(row) != expected_cols:
raise ValueError(f"第 {i} 行:{len(row)} 列,预期 {expected_cols} 列")csv.reader
The
strict=True
parameter is not superfluous either. According to the documentation, the default Dialect uses commas and sets
strict=False
, so malformed CSV passes through silently. With strict enabled, errors stop at the parser layer instead of continuing to pollute downstream data.
Step 5: Lock in the parser's behavior with golden tests
The parser works now. The problem is that next week a colleague might add
errors="replace"
to "reduce errors," or swap the order in which encodings are tried.
The TensorFlow Federated documentation defines golden tests this way: use them when you want developers to know their code has changed a function's output.
A CSV parser's normalized output is a natural fit for this.
# tests/test_golden.py(节选)
import json, os
from pathlib import Path
import pytest
from customer_csv import parse_file
HERE = Path(__file__).parent
@pytest.mark.parametrize("name", ["bom_semicolon.csv"])
def test_golden(name):
rows = parse_file(HERE / "fixtures" / name, expected_cols=3)
actual = json.dumps(rows, ensure_ascii=False, indent=2)
gold = HERE / "golden" / f"{name}.json"
if os.environ.get("UPDATE_GOLDEN"):
gold.parent.mkdir(exist_ok=True)
gold.write_text(actual, encoding="utf-8")
assert actual == gold.read_text(encoding="utf-8")Run
UPDATE_GOLDEN=1 pytest
the first time to generate the reference file, then open the JSON and verify it cell by cell. If you'd rather not write your own, the pytest-goldie plugin provides a
golden
fixture and a
update_goldens
flag for overwriting saved output.
The most common mistake with golden tests is updating the reference file without reading it. The TensorFlow Federated documentation emphasizes that after regenerating golden files, you must review the diff for unexpected changes. "Wałęsa" turning into "Wałęsa" in the diff is exactly the cp1258 mis-selection bug that step 2 warned about.
How does this skill play out at a customer site?
On your first day at the customer, before writing a single line of transformation code, ask each source system for three to five sample files. Put them all into
tests/fixtures
, including the broken ones, and create a golden test for each file.
When a new file from the customer breaks the parser, add it to the fixtures, fix the code, and then read the diff. Every incident becomes a new test.
When reading FDE job postings, watch for descriptions about integrating or onboarding customer data: when such phrases appear, that is exactly this work. Don't just write "CSV processing" on your resume.
Be more specific, for example: built a golden test suite for customer data imports that caught encoding bugs before the data reached production. A small repository with real, anonymized fixtures is more convincing than such a description.
There will always be bugs in customer data that you've never seen before. Golden tests guarantee that every bug you've fixed will never quietly come back.
Was this article helpful?
Thanks for your feedback!