Skip to main content
Editor

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()
import csv
import io
data = '''name,age,city
Alice,30,New York
Bob,25,London
Charlie,35,Tokyo'''
f = io.StringIO(data)
reader = csv.reader(f)
for row in reader:
print(row)
Output
['name', 'age', 'city']
['Alice', '30', 'New York']
['Bob', '25', 'London']
['Charlie', '35', 'Tokyo']

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()
import csv
import io
data = '''name,age,city
Alice,30,New York
Bob,25,London'''
f = io.StringIO(data)
reader = csv.reader(f)
# Skip the header row
header = next(reader)
print(f'Columns: {header}')
print('---')
# Process data rows
for row in reader:
name, age, city = row
print(f'{name} is {age} years old and lives in {city}')
Output
Columns: ['name', 'age', 'city']
---
Alice is 30 years old and lives in New York
Bob is 25 years old and lives in London

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()
import csv
import io
f = io.StringIO()
writer = csv.writer(f)
# Write the header
writer.writerow(['name', 'score', 'grade'])
# Write data rows
writer.writerow(['Alice', '95', 'A'])
writer.writerow(['Bob', '82', 'B'])
writer.writerow(['Charlie', '78', 'C'])
# Read back what we wrote
f.seek(0)
print(f.read())
Output
name,score,grade
Alice,95,A
Bob,82,B
Charlie,78,C

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

Writing multiple rows at once
import csv
import io
f = io.StringIO()
writer = csv.writer(f)
rows = [
['fruit', 'color', 'count'],
['apple', 'red', '5'],
['banana', 'yellow', '3'],
['grape', 'purple', '12'],
]
writer.writerows(rows)
f.seek(0)
print(f.read())
Output
fruit,color,count
apple,red,5
banana,yellow,3
grape,purple,12

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
import csv
import io
data = '''name,age,city
Alice,30,Paris
Bob,25,Berlin'''
f = io.StringIO(data)
reader = csv.DictReader(f)
for row in reader:
print(f'{row["name"]} is {row["age"]} and lives in {row["city"]}')
Output
Alice is 30 and lives in Paris
Bob is 25 and lives in Berlin

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
import csv
import io
f = io.StringIO()
fieldnames = ['name', 'score']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'name': 'Alice', 'score': '95'})
writer.writerow({'name': 'Bob', 'score': '87'})
f.seek(0)
print(f.read())
Output
name,score
Alice,95
Bob,87
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
import csv
import io
data = '''product,price,in_stock
Laptop,999,yes
Mouse,25,no
Keyboard,75,yes
Monitor,300,yes'''
f = io.StringIO(data)
reader = csv.DictReader(f)
print('In-stock items:')
for row in reader:
if row['in_stock'] == 'yes':
print(f' {row["product"]}: ${row["price"]}')
Output
In-stock items:
  Laptop: $999
  Keyboard: $75
  Monitor: $300

Calculating totals

Calculating averages from CSV data
import csv
import io
data = '''student,math,science
Alice,90,85
Bob,78,92
Charlie,88,79'''
f = io.StringIO(data)
reader = csv.DictReader(f)
total_math = 0
count = 0
for row in reader:
total_math += int(row['math'])
count += 1
average = total_math / count
print(f'Average math score: {average:.1f}')
Output
Average math score: 85.3

How Do You Handle Different Delimiters?

Reading tab-separated data
import csv
import io
# Tab-separated data
tsv_data = 'name\tscore\nAlice\t95\nBob\t82'
f = io.StringIO(tsv_data)
reader = csv.reader(f, delimiter='\t')
for row in reader:
print(row)
Output
['name', 'score']
['Alice', '95']
['Bob', '82']

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
import csv
import io
data = 'name,age,city\nAlice,30,Paris\nBob,25,Berlin\nCharlie,35,Tokyo'
f = io.StringIO(data)
reader = csv.reader(f)
header = next(reader)
people = []
for row in reader:
person = dict(zip(header, row))
people.append(person)
for p in people:
print(p)
Output
{'name': 'Alice', 'age': '30', 'city': 'Paris'}
{'name': 'Bob', 'age': '25', 'city': 'Berlin'}
{'name': 'Charlie', 'age': '35', 'city': 'Tokyo'}

Finding the maximum value in a column

Finding the highest score
import csv
import io
data = 'player,score\nAlice,85\nBob,92\nCharlie,78\nDiana,96'
f = io.StringIO(data)
reader = csv.DictReader(f)
best_player = ''
best_score = 0
for row in reader:
score = int(row['score'])
if score > best_score:
best_score = score
best_player = row['player']
print(f'Winner: {best_player} with {best_score} points')
Output
Winner: Diana with 96 points

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
import csv
import io
f = io.StringIO()
writer = csv.writer(f)
# This value contains a comma
writer.writerow(['address', 'city'])
writer.writerow(['123 Main St, Apt 4', 'Springfield'])
writer.writerow(['456 Oak Ave', 'Portland'])
f.seek(0)
print(f.read())
Output
address,city
"123 Main St, Apt 4",Springfield
456 Oak Ave,Portland

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
import csv
import io
csv_data = 'name,age\nAlice,30\nBob,25\nCharlie,35'
f = io.StringIO(csv_data)
# Your code here
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'])
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'])
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='').

import csv
import io
f = io.StringIO()
# Your code here: create writer, write header and rows, seek and print
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
import csv
import io
data = 'item,price\nBook,20\nPen,5\nBag,95'
f = io.StringIO(data)
reader = csv.DictReader(f)
total = 0
for row in reader:
total += row['price']
print(f'Total: {total}')
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
import csv
import io
data = 'name,score\nAlice,95\nBob,72\nCharlie,90\nDiana,88\nEve,91'
f = io.StringIO(data)
# Your code here

Harder problems

More problems on this topic: Working with data

Related Tutorials

Was this tutorial helpful?