Python CSV: Read, Write, and Process CSV Files
Think about a spreadsheet with rows and columns — names in one column, ages in another, scores in a third. A CSV file (Comma-Separated Values) is just a plain text version of that spreadsheet, where commas separate each column.
CSV is one of the most common data formats on the planet. You'll find it in Excel exports, database dumps, data science datasets, and API downloads. If you work with data, you will work with CSV files.
Python has a built-in csv module that makes reading and writing CSV data easy and reliable. In this tutorial, you'll learn how to use it. We'll simulate CSV files with io.StringIO so everything runs right in your browser.
How Do You Read a CSV File in Python?
The csv.reader() function takes a file object and returns an iterator. Each iteration gives you one row as a list of strings.
Each row is a list of strings. Notice that '30' is a string, not a number. CSV files store everything as text, so you need to convert values yourself when you need numbers.
The first row usually contains headers — column names that describe what each value means. You can skip it or use it to label your data.
How Do You Write a CSV File in Python?
The csv.writer() function creates a writer object. You use writerow() to write one row at a time, or writerows() to write multiple rows at once.
You can also write multiple rows at once using writerows(), which takes a list of lists.
What Are DictReader and DictWriter?
With csv.reader, you access columns by index number — row[0], row[1]. That works, but row[0] doesn't tell you what the value means. Was it the name? The age?
csv.DictReader solves this by turning each row into a dictionary where the keys are the column names from the header. This makes your code much more readable.
csv.DictWriter is the opposite — it writes dictionaries to CSV. You tell it the column names (fieldnames), and it handles the rest.
for row in reader:
name = row[0] # Unclear
age = row[1] # What is index 1?for row in reader:
name = row['name'] # Clear!
age = row['age'] # Readable!How Do You Process and Transform CSV Data?
Reading and writing are the basics. In practice, you'll often need to filter rows, calculate totals, or transform data. Let's look at some common patterns.
Filtering rows
Calculating totals
How Do You Handle Different Delimiters?
You can also use csv.Sniffer to auto-detect the delimiter, but specifying it explicitly is more reliable.
What Are Common CSV Processing Patterns?
Let's look at a few patterns you'll use repeatedly when working with CSV data in real projects.
Converting CSV rows to dictionaries manually
Sometimes you want a list of dictionaries from CSV data so you can work with it more easily. While DictReader does this for you, understanding the manual approach helps you handle non-standard data.
Finding the maximum value in a column
Quoting in CSV output
If your data contains commas, newlines, or quotes, the csv.writer automatically adds quotes around those values to keep the CSV valid.
Practice Exercises
Given the CSV data below (already stored in csv_data), use csv.reader to read it and print only the name column from each data row (skip the header).
The data:
name,age
Alice,30
Bob,25
Charlie,35Expected output:
Alice
Bob
CharlieWhat does this code print? Think about how DictReader maps column names to values.
import csv
import io
data = 'color,count\nred,3\nblue,7'
f = io.StringIO(data)
reader = csv.DictReader(f)
for row in reader:
print(row['count'])Use csv.writer to create a CSV string with a header row ['item', 'qty'] and two data rows: ['Apples', '5'] and ['Bananas', '3'].
Then seek back to the start and print the result with print(f.read(), end='').
This code tries to calculate the total price from CSV data, but it produces a wrong result. Fix the bug.
Expected output:
Total: 120Given student grade data, count how many students scored 90 or above in the score column and print the result.
The CSV data:
name,score
Alice,95
Bob,72
Charlie,90
Diana,88
Eve,91Expected output:
High scorers: 3