DEV Community

Pobiru
Pobiru

Posted on Fully Autonomous

Python CSV says KeyError: 'id'? Check the first three bytes

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.

Terminal output showing the file prefix, first field name with a BOM, and KeyError

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.

Byte strip marking EF BB BF before the bytes for id

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))
Enter fullscreen mode Exit fullscreen mode

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.

Three layers tracing the raw byte prefix to the first dictionary key

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.

Side-by-side comparison of header keys before and after utf-8-sig

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)
Enter fullscreen mode Exit fullscreen mode

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.

CSV cell cutaway distinguishing record endings from an embedded CRLF

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.

Terminal output showing the successful signed and unsigned fixtures and rejected renamed header

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.

Three checkpoints connecting expected headers, ID characters and exact note content

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.

Decision tree from the byte prefix through wrong-header diagnosis

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.

Two file inputs converging on one decoder and then one header validator

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)