Your spreadsheet shows a column called id. Python raises KeyError: 'id'. Before renaming anything, print repr(reader.fieldnames). In a small test file with a UTF-8 byte-order mark (BOM), the first key is actually '\ufeffid'.
In the failing run below, the second key reads normally; the invisible character is attached to the first one.
Find the signature
Check three bytes, then check the decoded names. The file starts with EF BB BF, immediately followed by the ASCII bytes for id. The signature belongs to the start of the file, not to the name of your column.
from pathlib import Path
import csv
path = Path("inventory.csv")
with path.open("rb") as stream:
print(stream.read(3).hex(" "))
with path.open(encoding="utf-8", newline="") as stream:
print(repr(csv.DictReader(stream).fieldnames))
With plain utf-8, those first three bytes decode to a literal U+FEFF. DictReader takes the header it receives, which explains why "id" fails even though the second key, "note", works.
Decode the file before checking its schema
On known UTF-8 input, use utf-8-sig at the file boundary. It consumes a UTF-8 BOM at the start when present and reads ordinary UTF-8 the same way when absent.
def read_inventory(path):
with path.open(encoding="utf-8-sig", newline="") as stream:
reader = csv.DictReader(stream)
if reader.fieldnames != ["id", "note"]:
raise ValueError(f"unexpected headers: {reader.fieldnames!r}")
return list(reader)
The codec and newline="" do separate jobs. The codec handles the optional signature. Passing newline="" leaves line endings available to the CSV parser, including CRLF inside a quoted cell.
Test both files, not just the one that failed
The local run used the same payload with and without the signature. Both kept the leading zeros in 0007 and the CRLF inside the quoted note. A third file with sku in place of id still failed validation.
Check the field names and exact values, not just the row count. One returned row tells you nothing about whether the ID still has its zeros or the note still has its line break.
If there's no signature and the first header still looks wrong, inspect the header representation and the expected schema. utf-8-sig is not an encoding detector or a fix for a different delimiter.
Keep this fix at the file boundary. Stripping U+FEFF from the entire decoded string would also change field values containing that character. A header check can still report the names it actually received.
References: Python CSV reader, Python codec documentation.
AI disclosure: AI drafted this article and generated the diagrams. The output images show a local Python run against synthetic fixtures.









Top comments (0)