Read a UTF-8 CSV by Column Name in Python

Last updated: December 4, 2026.

Use csv.DictReader when the first CSV record contains column names. For a simple import, the standard library can read the file one row at a time and handle commas or line breaks inside quoted fields.

import csv

with open("students.csv", encoding="utf-8-sig", newline="") as source:
    rows = csv.DictReader(source, strict=True)
    required = {"name", "age", "course"}
    header = rows.fieldnames or []
    if set(header) != required or len(header) != len(required):
        raise ValueError("Expected name, age and course exactly once")

    for row in rows:
        if None in row or any(value is None for value in row.values()):
            raise ValueError(f"Wrong column count at line {rows.line_num}")

        age = int(row["age"])
        print(row["name"], age, row["course"])

Use the file’s actual encoding and delimiter

utf-8-sig reads UTF-8 with or without the optional byte-order mark. This prevents a spreadsheet export’s mark from becoming part of the first header name. It does not decode files in other encodings. If decoding fails, identify the export’s encoding before choosing a different one.

Use newline="" so the CSV module controls newline handling, including embedded newlines in quoted fields. For a semicolon-separated export, pass delimiter=";" to the reader. Avoid splitting lines by hand because commas inside quotes belong to the field.

Validate the row shape before conversion

The sample allows the three expected headers in any order and rejects duplicate names. By default, DictReader assigns trailing fields without a header to the key None and fills missing fields with the value None. A present empty field is an empty string and should be validated separately when required.

CSV values arrive as strings. Convert only fields that truly need numeric types. Keep identifiers with significant leading zeros as strings. If a bad record should be reported with context, catch conversion errors at the import boundary and include the line number.

Documentation

Related guides

Sergey Kornilov

Sergey Kornilov