Skip to course content
Free course

Python Foundations / Module 7 / CSV Structure and Types

Module 7 lesson

CSV Structure and Types

Unit ID: M07-U03 Estimated active time: 25-35 minutes

CSV is structured text

Example:

code,title,hours,status
AI-01,AI Foundations,8,available

Commas separate fields and the first row provides headers. Quoted fields may contain commas, so line.split(",") is not a reliable CSV parser.

Read with DictReader

import csv

with source_path.open("r", encoding="utf-8", newline="") as file:
    reader = csv.DictReader(file)
    rows = list(reader)

Each row is a dictionary keyed by the headers.

CSV fields begin as text

print(rows[0]["hours"])
print(type(rows[0]["hours"]))

The value 8 from the file is text until your program validates and converts it.

Check headers

required_fields = {"code", "title", "hours", "status"}
actual_fields = set(reader.fieldnames or [])
missing_fields = required_fields - actual_fields

Reject a file missing required headers before processing rows.

Row numbers

The header is physical line 1, so the first data row is normally line 2. Record a clear source_row value in rejection evidence.

Write CSV with DictWriter

with output_path.open("w", encoding="utf-8", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=["code", "title", "hours", "status"])
    writer.writeheader()
    writer.writerows(records)

Use an explicit field order. Do not overwrite the source file.

Practice

Read the supplied CSV, inspect headers, row count, raw hours type, and one full row. Predict which rows will fail validation before converting anything.

Takeaway

Use the CSV module to respect quoting and delimiters. Validate headers, remember that fields start as text, and retain source row numbers. Next, we will work with JSON's nested typed structure.