Module 13 · File Handling — topic 10 of 15
CSV files
Comma-separated values with the csv module: reader and writer, DictReader and DictWriter, quoting of commas and quotes, newline="", and summarising tabular data.
Learning objectives
- Read and write CSV with csv.reader and csv.writer
- Use DictReader and DictWriter with headers
- Aggregate data from a CSV file
Definition
A CSV (comma-separated values) file stores a table as text, one row per line, with fields separated by commas. Python's csv module reads and writes CSV correctly, including fields that contain commas, quotes or newlines.
Introduction
Spreadsheets, bank statements and data exports are often CSV files. Splitting lines on commas yourself breaks as soon as a field contains a comma — the csv module handles that properly.
Why it matters
CSV is the most common exchange format for tabular data. Reading it correctly is a basic skill for automation and data work.
Detailed explanation
Always open CSV files with newline="" so the csv module controls line endings itself, and specify the encoding.
csv.reader(f) yields each row as a list of strings; csv.writer(f).writerow(list) writes one row and writerows(rows) writes many.
csv.DictReader(f) uses the first row as field names and yields each row as a dictionary. csv.DictWriter(f, fieldnames=[...]) writes dictionaries; call writeheader() first.
Fields containing commas, quotes or newlines are wrapped in double quotes, and embedded quotes are doubled — the module does this automatically.
Every value read from a CSV file is a string. Convert with int() or float() before calculating.
Other delimiters (semicolon, tab) are supported with delimiter=";" or "\t".
For heavy data analysis, pandas.read_csv is common, but the csv module needs no installation and is perfect for scripts.
Syntax
- Open with newline="".
- DictReader uses the header row.
- Values are strings; convert them.
Code examples
Writing and reading rows
['name', 'city', 'marks'] ['Asha', 'Pune', '91'] ['Ravi', 'Delhi, NCR', '78']
Automatic quoting
['item,note', 'pen,"blue, fine tip"', 'book,"says ""hello"""']
More examples
Summarising sales by region
{'North': 430, 'South': 380}
['region,total', 'North,430', 'South,380']Step-by-step explanation
- DictReader turns each data row into a dictionary keyed by the header.
- amount is converted with int() before adding.
- The summary is written as a new CSV with its own header row.
Expected output
Running “Summarising sales by region” prints exactly:
Practical applications
- Importing bank statements into a budgeting script.
- Exporting reports for spreadsheet users.
Best practices
- Use the csv module, never manual splitting.
- Prefer DictReader/DictWriter for readability.
- Convert types explicitly.
Common mistakes
Splitting on commas manually
Avoid
Prefer
"Delhi, NCR" would be split into two fields.
Forgetting newline=""
Avoid
Prefer
On Windows you get blank lines between rows.
Important notes
- Excel may expect encoding="utf-8-sig" to detect UTF-8 correctly.
Key takeaways
- csv.reader/writer handle lists; DictReader/DictWriter handle dictionaries.
- Open CSV files with newline="".
- All values read are strings.
Try it yourself
- 1Read a CSV of students and write a new CSV containing only those with marks above 80.
- 2Compute the average of a numeric column in a CSV file.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?