Read a CSV file as dictionaries
Stream CSV rows as dicts keyed by header with csv.DictReader, handling UTF-8 BOMs and quoted commas.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
import csv
def read_csv(path):
with open(path, newline="", encoding="utf-8-sig") as handle:
yield from csv.DictReader(handle)Example / expected output
for row in read_csv("users.csv"):
print(row["email"])How it works
Open files with newline="" so the csv module handles embedded newlines itself, and utf-8-sig so a BOM from Excel does not become part of the first header name. The generator yields one row at a time, so large files do not fill memory.
Related snippets
- PHP Tested
Read a large CSV file with a generator
Stream CSV rows as associative arrays using fgetcsv, without loading the whole file into memory.
- Bash
Delete files older than N days
Safely remove old log or temp files with find, previewing first and handling unusual filenames.
- Python Tested
Write a file atomically
Write to a temporary file and rename it into place so readers never see a half-written file.
- Bash
Timestamped tar.gz backup that keeps the newest N
Archive a directory with a sortable timestamp and delete older backups beyond a retention count.

