Validate CSV files in Python: headers, missing fields, and bad records
By StringClass · Published
Parse the CSV with csv.reader, validate its header before making dictionaries, then check each record against an explicit schema. Keep errors separate and process the dataset only after validation succeeds.
Before you start: You know Python functions, lists, dictionaries, and exceptions. The examples use only standard-library modules and synthetic customer data.
Decide what a valid CSV means
A CSV parser can read a file without proving that the records make sense for your application. A row might have too few cells, a blank customer ID, or an invalid timestamp. Validate those rules before merging or deduplicating records, so a missing value does not silently replace good data.
This example accepts customer exports with three columns, in this order: customer_id, name, and updated_at. Its contract is:
- Headers must match exactly, including order and spelling. Repeated or extra headers are rejected.
- Every record must contain exactly three cells. A missing cell differs from a present but empty cell.
- Trim surrounding whitespace from IDs, preserving case and leading zeros. Reject a blank ID. Names may be empty and are otherwise preserved.
- Require UTC timestamps in
YYYY-MM-DDTHH:MM:SSZformat, with a valid calendar date. - Accept a header-only file as an empty dataset. Reject an empty file with no header.
- Collect record-level errors, but return no usable rows if any error occurred. Repair the export before continuing.
These rules fit our customer example. A file with a different schema needs its own contract; accepting arbitrary headers and then guessing their meaning is not validation.
Missing cells and blank values differ
Consider these records:
customer_id,name,updated_at
001,,2026-10-20T09:00:00Z
002,Bo
003,"River, Sam",2026-10-21T10:00:00Z
The first record contains all three cells and an intentionally empty name, which our rules allow. The second lacks the timestamp cell. The third contains a quoted comma inside its name and is structurally valid. Do not split each line on commas: that would turn the third record into the wrong number of fields.
Blank physical lines are skipped by Python's CSV reader. A quoted field may also contain a newline. Consequently, the record number in the validation messages below counts data records, not physical file lines.
A complete standard-library validator
The function takes text, returns a dictionary with rows and errors, and uses no external packages. Duplicate IDs are allowed at this stage because selecting the latest version is a separate operation.
import csv
from datetime import datetime, timezone
from io import StringIO
def validate_customers(csv_text):
required = ["customer_id", "name", "updated_at"]
reader = csv.reader(StringIO(csv_text, newline=""), strict=True)
rows, errors = [], []
try:
header = next(reader, None)
if header != required:
return {"rows": [], "errors": [
"Expected header: customer_id,name,updated_at"
]}
for record_number, cells in enumerate(reader, start=1):
if len(cells) != len(required):
errors.append(f"Record {record_number}: expected 3 cells")
continue
row = dict(zip(required, cells))
row["customer_id"] = row["customer_id"].strip()
if not row["customer_id"]:
errors.append(f"Record {record_number}: blank customer_id")
try:
updated = datetime.strptime(
row["updated_at"], "%Y-%m-%dT%H:%M:%SZ"
).replace(tzinfo=timezone.utc)
normalized = updated.isoformat(timespec="seconds").replace(
"+00:00", "Z"
)
if normalized != row["updated_at"]:
raise ValueError("Non-canonical timestamp")
except ValueError:
errors.append(f"Record {record_number}: invalid UTC timestamp")
rows.append(row)
except csv.Error:
errors.append("Malformed CSV quoting or field size limit exceeded")
return {"rows": [] if errors else rows, "errors": errors}
strict=True reports parser-detected malformed CSV. It does not enforce your column schema or catch every business-data problem, which is why the explicit checks still matter. The reader also has a field-size limit; an unusually large field produces a parsing error rather than an unlimited allocation.
Using csv.reader first lets us validate the header before making dictionaries. With repeated headers, immediately constructing dictionaries could overwrite one field's value with another.
Read an export and inspect the result
Save the following program with the function above and run it with Python 3.10 or later:
sample = (
"customer_id,name,updated_at\n"
"001,,2026-10-20T09:00:00Z\n"
"002,Bo\n"
",Cy,2026-02-30T10:00:00Z\n"
)
result = validate_customers(sample)
print(result["rows"])
print(result["errors"])
Expected output:
[]
['Record 2: expected 3 cells', 'Record 3: blank customer_id', 'Record 3: invalid UTC timestamp']
The valid first record is not returned because the whole dataset failed validation. This prevents a caller from unknowingly processing only part of the export. A different application might intentionally quarantine invalid rows, but that policy should be explicit and separately reported.
For a real UTF-8 export, open it with encoding="utf-8-sig" to accept an optional byte order mark and newline="" for CSV newline handling. Pass the text to this function, inspect errors, and proceed only when that list is empty. This example holds the input and results in memory; large exports need streaming and bounded error reporting.
Checks worth keeping
Test an empty file, a header-only file, a repeated header, too many cells, too few cells, an empty allowed name, a quoted comma, and an impossible calendar date. Include ID 001 so a mistaken conversion to an integer is caught. A timestamp such as 2026-1-1T00:00:00Z must fail our fixed-format rule even if a date parser can understand it.
Try it yourself
Repair the two invalid sample records and check that all three rows are returned. Then add a later version of ID 001. The validator should accept both versions: validating records does not decide which version to retain.
Continue with deduplicating CSV records while keeping the latest version to apply that second rule. Keep validation errors separate from deduplication decisions so the workflow stays explainable.
Reference: Python's CSV documentation covers quoting, newline handling, parsing errors, and reader limits.