Read UTF-8 CSV in Python with BOM and Header Validation

A CSV export looks correct in a text editor, but an importer cannot find its id column. Another export imports without an error while silently losing a column because two headers share the same name.

Handle these as separate input problems: decode the file correctly, validate its header, and check each record’s width before building dictionaries. The following Python 3 utility reads a small, known CSV format using only the standard library.

Reproduce the Invisible Header Prefix

A UTF-8 byte order mark (BOM) is the three-byte prefix EF BB BF. Decoding it with ordinary utf-8 leaves a leading \ufeff character in the first header:

1
2
3
4
5
6
7
8
9
import csv
import io

raw = b"\xef\xbb\xbfid,name,note\r\n001,Ada,ready\r\n"
wrong = next(csv.reader(io.StringIO(raw.decode("utf-8"))))
right = next(csv.reader(io.StringIO(raw.decode("utf-8-sig"))))

print(repr(wrong[0]))  # '\ufeffid'
print(repr(right[0]))  # 'id'

Python’s utf-8-sig codec skips an optional BOM at the beginning when decoding. It also accepts UTF-8 files without that prefix. It does not detect arbitrary spreadsheet encodings: a UTF-16 export or legacy code-page file needs its own explicit encoding contract.

Do not remove \ufeff from every cell. An encoding signature belongs at the beginning of the byte stream; changing characters throughout the data would be a separate transformation.

Define the Import Contract

For this example, the export describes a small player or asset table:

PropertyRule
EncodingUTF-8, with or without an initial BOM
CSV syntaxComma delimiter, double-quoted fields, doubled embedded quotes
HeaderExactly id, name, and note, each once, in any order
Header spellingCase-sensitive, with no trimming or renaming
Data recordsExactly three fields, including explicitly empty fields
ValuesStrings; preserve leading zeros, spaces, and embedded line endings
Blank recordsRejected; a final line terminator alone is allowed

An empty note is structurally valid; a missing third field is not. This utility checks the table’s shape. Required values, unique player IDs, and domain-specific limits belong in a subsequent validation step.

Use an explicit dialect for a known export. Automatically guessing the delimiter can turn a malformed file into a different, apparently valid table. The first record must be the header; this contract does not support a preamble or comment lines.

Validate Before Constructing Dictionaries

Save this module as csv_import.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import csv

EXPECTED_HEADERS = {"id", "name", "note"}


def read_csv_records(path):
    records = []
    with open(path, "r", encoding="utf-8-sig", newline="") as source:
        reader = csv.reader(source, dialect="excel", strict=True)
        try:
            headers = next(reader, None)
            if headers is None:
                raise ValueError("CSV is empty; expected a header")
            if len(headers) != len(set(headers)):
                raise ValueError("CSV header contains duplicate names")
            if set(headers) != EXPECTED_HEADERS:
                raise ValueError("CSV header must contain id, name, and note")

            for fields in reader:
                if len(fields) != len(headers):
                    raise ValueError(
                        f"CSV record ending at line {reader.line_num}: "
                        f"expected {len(headers)} fields, got {len(fields)}"
                    )
                records.append(dict(zip(headers, fields)))
        except csv.Error as error:
            raise ValueError(
                f"CSV parsing failed near line {reader.line_num}: {error}"
            ) from error
    return records

The csv reference explains newline="", quoted fields, and parser options. strict=True catches parser errors such as an unfinished quoted field; it does not enforce header uniqueness or record width. Those checks remain explicit here.

DictReader is convenient after a schema is trusted, but duplicate names cannot represent independent dictionary keys. Its defaults also accommodate short or long rows. Reading lists first lets this importer reject those cases before any values are mapped to keys.

The error reports the physical line where a record ends. A quoted field can span several lines, so that number is not a record index. Avoid split(",") and manual line-by-line splitting: a comma or newline inside quotes can be part of one value.

Process Only a Fully Validated Table

After saving the module, this example creates a small export and imports it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import json
from pathlib import Path

from csv_import import read_csv_records

path = Path("players.csv")
path.write_bytes(
    b'\xef\xbb\xbfid,name,note\r\n001,Ada,"ready, set"\r\n'
)
records = read_csv_records(path)
print(json.dumps(records))
# [{"id": "001", "name": "Ada", "note": "ready, set"}]

The id remains "001"; numeric conversion would discard its leading zeros. The function returns only after reading and validating the entire file, and the context manager closes the source even when validation fails. A later malformed row therefore prevents the caller from receiving a partial table.

This design keeps all records in memory and suits bounded configuration files. Set upload and record-count limits for your application. For a large import, stream into a staging area and commit only after validation, rather than performing irreversible updates as each record arrives. Operating-system and decoding errors propagate to the caller; report those alongside structural errors at the import boundary.

Test BOM, Quoting, and Invalid Shapes

Save this as test_csv_import.py beside the module and run python3 test_csv_import.py using your Python 3 interpreter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import tempfile
from pathlib import Path

from csv_import import read_csv_records


def must_reject(path, raw, exception=ValueError):
    path.write_bytes(raw)
    try:
        read_csv_records(path)
    except exception:
        return
    raise AssertionError("Expected the import to fail")


with tempfile.TemporaryDirectory() as directory:
    path = Path(directory) / "input.csv"
    text = 'id,name,note\r\n001,Zo\u00eb,"a,b\r\nc"\r\n002,Ada,\r\n'
    expected = [
        {"id": "001", "name": "Zo\u00eb", "note": "a,b\r\nc"},
        {"id": "002", "name": "Ada", "note": ""},
    ]
    for prefix in (b"", b"\xef\xbb\xbf"):
        path.write_bytes(prefix + text.encode("utf-8"))
        assert read_csv_records(path) == expected

    path.write_bytes(b'note,id,name\n"He said ""go""",007,Ada\n')
    assert read_csv_records(path) == [
        {"note": 'He said "go"', "id": "007", "name": "Ada"}
    ]
    path.write_bytes(b"id,name,note\n")
    assert read_csv_records(path) == []  # Header-only table is valid.

    for raw in (
        b"",
        b"\xef\xbb\xbf",
        b"\nid,name,note\n",
        b"id,name,name\n001,Ada,ready\n",
        b"id,name,note,note\n001,Ada,x,y\n",
        b"id,name,extra\n001,Ada,x\n",
        b"id, name,note\n001,Ada,x\n",
        b"id,name,note\n001,Ada\n",
        b"id,name,note\n001,Ada,x,extra\n",
        b"id,name,note\n\n",
        b'id,name,note\n001,Ada,"unfinished',
        b"id,name,note\n001,Ada,ok\n002,Bob\n",
    ):
        must_reject(path, raw)
    must_reject(path, b"id,name,note\n001,\xff,x\n", UnicodeDecodeError)

print("CSV import checks passed")

Keep a real export fixture from your producer in the test suite as well. If it changes to semicolons, new columns, or a different encoding, update the documented contract and fixtures together instead of silently repairing each input.