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:
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:
| Property | Rule |
|---|---|
| Encoding | UTF-8, with or without an initial BOM |
| CSV syntax | Comma delimiter, double-quoted fields, doubled embedded quotes |
| Header | Exactly id, name, and note, each once, in any order |
| Header spelling | Case-sensitive, with no trimming or renaming |
| Data records | Exactly three fields, including explicitly empty fields |
| Values | Strings; preserve leading zeros, spaces, and embedded line endings |
| Blank records | Rejected; 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:
| |
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:
| |
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:
| |
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.