Intermediate level · Module 1: Files and Structured Data in Python · Lesson 2 of 3
Processing CSV Files
Read spreadsheet exports as CSV, filter and summarise rows, and write new CSV files.
In this lesson you will
- Read rows as dictionaries with DictReader
- Write filtered results with DictWriter
Key concepts
CSVheader rowDictReader/DictWriternewline=''
The lesson
CSV (comma-separated values) is the most common format for exchanging tables: Excel, Google Sheets and survey tools such as KoboToolbox all export it. Python's csv module reads each row safely, including values that contain commas inside quotes.
csv.DictReader turns every row into a dictionary keyed by the column headings, so you can write row['amount'] instead of remembering column positions. Values always arrive as text; convert numbers with float() or int().
To write a CSV, use csv.DictWriter with the field names and newline='' when opening the file — without it, Windows adds blank lines between rows.
Step by step
- Open the sales CSV with DictReader and print the first row.
- Convert the amount to a number and filter sales above 20,000 SSP.
- Add up totals per product in a dictionary.
- Write the filtered rows to a new CSV with DictWriter.
Practice activity
From a CSV of 200 market sales, write a new CSV containing only sales above 20,000 SSP and print the total per product.
Expected result: A filtered CSV that opens correctly in Excel and a correct per-product total.
Check your understanding
-
What type are the values read by csv.DictReader?
Show answer
Strings; numeric fields must be converted with int() or float().
-
Why pass newline='' when writing CSV files?
Show answer
To prevent blank lines between rows on Windows.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.