Skip to main content

Python CSV: Read, Write, and Process CSV Files

Intermediate25 min5 exercises70 XP
0/5 exercises

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.

Reading CSV with csv.reader()
Loading editor...

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.

Skipping the header row with next()
Loading editor...

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.

Writing CSV with csv.writer()
Loading editor...

You can also write multiple rows at once using writerows(), which takes a list of lists.

Writing multiple rows at once
Loading editor...

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.

DictReader gives you named columns
Loading editor...

csv.DictWriter is the opposite — it writes dictionaries to CSV. You tell it the column names (fieldnames), and it handles the rest.

DictWriter writes dictionaries as CSV rows
Loading editor...
csv.reader — access by index
for row in reader:
    name = row[0]   # Unclear
    age = row[1]    # What is index 1?
csv.DictReader — access by name
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

Filtering CSV rows by a condition
Loading editor...

Calculating totals

Calculating averages from CSV data
Loading editor...

How Do You Handle Different Delimiters?

Reading tab-separated data
Loading editor...

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.

Building a list of dictionaries from CSV
Loading editor...

Finding the maximum value in a column

Finding the highest score
Loading editor...

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.

Automatic quoting for values with commas
Loading editor...

Practice Exercises

Read CSV and Print Names
Write Code

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,35

Expected output:

Alice
Bob
Charlie
Loading editor...
Predict the DictReader Output
Predict Output

What 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'])
Loading editor...
Build a CSV String
Write Code

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='').

Loading editor...
Fix the CSV Sum Bug
Fix the Bug

This code tries to calculate the total price from CSV data, but it produces a wrong result. Fix the bug.

Expected output:

Total: 120
Loading editor...
Filter and Count CSV Rows
Write Code

Given 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,91

Expected output:

High scorers: 3
Loading editor...