Skip to contentSkip to navigation

Module 08 · Lesson 04

CSV Files: Reading and Writing Tables

Handle spreadsheet-style data: read CSV rows with csv.reader and DictReader, convert their text to numbers, and write tables back out with csv.writer and DictWriter.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Read rows as lists
  • Rows as dictionaries
  • Write a table
  • Watch the warmest city win

Tables as text

A CSV file is a table saved as plain text: one row per line, values split by commas.

  • The format

    name,score on the first line is the header. Each line after it is one row.

  • reader

    csv.reader(f) gives each row as a list of strings.

  • DictReader

    csv.DictReader(f) gives each row as a dictionary keyed by the header.

  • writer

    csv.writer(f).writerow([...]) writes a row. Open the file with newline="".

Tables everywhere

CSV is the simplest way to move a table from one program to another.

  • SpreadsheetsExcel and Google Sheets can save and open CSV files.
  • Bank statementsMost banks let you download your spending as a CSV.
  • Sports statsMatch results and player scores are often shared as CSV tables.
  • Data setsMost data you can download for projects starts life as a CSV.

Looping over rows

This line reads a table one row at a time. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

loop:One pass of the loop for each data row.

Read and write tables

Pick an example, change it, then press Run. Say what you expect to see before you press. Each Run starts with no files, so every example writes its own.

Example 1 of 6Read rows

csv.reader turns each line into a list of strings.

Your turn: Skip the header row by calling next() on the reader before the loop.

Python
import csv
with open("pets.csv", "w", encoding="utf-8", newline="") as f:
    f.write("name,kind,age\nRex,dog,4\nTom,cat,2\n")
with open("pets.csv", encoding="utf-8", newline="") as f:
    for row in csv.reader(f):
        print(row)
Output
Press Run to see what it prints.

Watch the warmest city win

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. import csv
  2. lines = ["city,temp", "Oslo,3", "Rome,18"]
  3. warmest = None
  4. for row in csv.DictReader(lines):
  5. temp = int(row["temp"])
  6. if warmest is None or temp > warmest[1]:
  7. warmest = (row["city"], temp)
  8. print(warmest)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.A row with an empty value:

import csv
print(next(csv.reader(["a,,c"])))

0 of 6 answered

Common CSV misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

What a CSV file looks like

A CSV (comma-separated values) file is a plain text table. Each line is a row, and commas separate the columns. The first row is usually a header that names the columns:

name,city,age
Ana,Lisbon,31
Ben,Leeds,25

It looks easy enough to split each line on commas yourself, but real data contains surprises. A value can itself contain a comma, such as "Smith, John", in which case the value is wrapped in double quotes. A value can even contain a line break. Python's csv module understands all of these rules, so always use it instead of split(",").

Reading rows with csv.reader

Try it 1: edit me, then Run
import csv

with open("people.csv", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    header = next(reader)          # the first row
    for row in reader:
        print(row)                 # ['Ana', 'Lisbon', '31']
Output
Press Run to see what it prints.

csv.reader wraps an open file. Looping over it gives each row as a list of strings. next(reader) takes one row, which is the usual way to read the header before the loop handles the data rows. Pass newline="" when opening any CSV file; the csv module handles line endings itself and this setting stops them being changed on the way.

Everything is text

Every value a CSV reader gives you is a string, even if it looks like a number. "31" + "25" is "3125", not 56. Convert columns before doing maths:

Try it 2: edit me, then Run
total_age = 0
for name, city, age in reader:
    total_age += int(age)
Output
Press Run to see what it prints.

Unpacking the row into named variables, as above, makes the loop far easier to read than row[2]. Use float() for prices and measurements with decimals.

Rows as dictionaries: DictReader

When a file has a header, csv.DictReader is usually more convenient. Each row becomes a dictionary whose keys come from the header:

Try it 3: edit me, then Run
with open("people.csv", newline="", encoding="utf-8") as f:
    for person in csv.DictReader(f):
        print(person["name"], "is", person["age"])
Output
Press Run to see what it prints.

The header row is used for the keys and is not returned as data, so there is no need to skip it. Code that uses names like person["city"] keeps working even if someone adds a column or reorders the existing ones, which would silently break code that relies on positions. reader.fieldnames holds the list of column names.

Writing with csv.writer

Try it 4: edit me, then Run
rows = [["product", "price"], ["tea", 2.5], ["cake", 4.0]]
with open("menu.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerows(rows)
Output
Press Run to see what it prints.

writerow() writes one list as one line, and writerows() writes a whole list of lists. The writer converts numbers to text for you and adds quotes around any value that contains a comma or a quote. Again, open the file with newline=""; without it, Windows can end up with an extra blank line between rows.

Writing dictionaries with DictWriter

csv.DictWriter writes dictionaries. You tell it the column order with fieldnames, and call writeheader() once before the rows:

Try it 5: edit me, then Run
people = [{"name": "Ana", "age": 31}, {"name": "Ben", "age": 25}]
with open("out.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "age"])
    writer.writeheader()
    writer.writerows(people)
Output
Press Run to see what it prints.

A dictionary with a key that is not in fieldnames raises a ValueError, which catches typos early. A missing key is written as an empty cell.

Other separators

Not every "CSV" uses commas. Files from some countries and programs use semicolons, and tab-separated files are common too. Pass delimiter: csv.reader(f, delimiter=";") or delimiter="\t". The same argument works for the writers.

Messy real-world rows

Files typed by people are rarely perfect. Cells may have stray spaces, such as " 12 ", which int() happily accepts but which spoil comparisons between names. A row may be completely empty, or have fewer cells than the header, in which case DictReader fills the missing keys with None. A quick clean-up step at the start of the loop saves a lot of confusion later: strip each name, skip rows whose important cells are empty, and convert the numbers once. If a value cannot be converted at all, the error lessons in the next module show how to report the bad row and carry on instead of stopping the whole program.

A typical job: read, process, write

Most CSV programs follow the same three steps. Read the rows into a list, usually of dictionaries. Process them in memory: convert types, filter, sort, total. Then write the results to a new file, leaving the original untouched so you can always run the program again. Keeping the steps separate, ideally in small functions, makes the program easy to test and change.

CSV or JSON?

CSV suits flat tables where every row has the same columns, and anyone can open it in a spreadsheet. JSON suits nested data, such as an order holding a list of items, and keeps types like numbers and booleans. Choose CSV when people will look at the data in a spreadsheet, and JSON when programs will exchange structured records.

Syntax

The general shape of the statements in this lesson.

syntax.py
import csv
with open("in.csv", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)            # rows as lists of strings
    header = next(reader)
    for row in reader: ...
with open("in.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):     # rows as dictionaries
        row["price"]
with open("out.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows(rows)
    w = csv.DictWriter(f, fieldnames=["a", "b"])
    w.writeheader(); w.writerows(dicts)
csv.reader(f, delimiter=";")
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Totals from a sales export

Beginner

A shop exports its sales as CSV. Work out the total revenue and the revenue per product, printing products in alphabetical order.

Python
import csv

with open("sales.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows([
        ["product", "qty", "price"],
        ["mug", "3", "6.50"],
        ["lamp", "1", "24.00"],
        ["mug", "2", "6.50"],
        ["candle", "4", "3.25"],
    ])

revenue = {}
with open("sales.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        amount = int(row["qty"]) * float(row["price"])
        revenue[row["product"]] = revenue.get(row["product"], 0) + amount

for product in sorted(revenue):
    print(f"{product}: {revenue[product]:.2f}")
print(f"Total: {sum(revenue.values()):.2f}")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The first block creates the sample export. DictReader gives each row as a dictionary keyed by the header, and int and float turn the text into numbers before multiplying. The dictionary collects a running total per product.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Adding numbers that are still text

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
row = {"qty": "2", "price": "3"}
print(row["qty"] * row["price"])
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

TypeError: can't multiply sequence by non-int of type 'str'

Write this instead

row = {"qty": "2", "price": "3"}
print(int(row["qty"]) * float(row["price"]))

Why it happens

Every value read from a CSV is a string, so the numbers must be converted first.

In the real world

Where this shows up in software people use every day.

  1. Converting a bank statement

    Personal finance

    A budgeting app imports bank statements that use semicolons as separators. It reads them, sorts spending into categories and writes a clean summary CSV for the user.

    Why Python fits

    delimiter=";" reads the semicolon file. Negative amounts are spending, so they are turned positive and added per shop. sorted(spent.items()) gives (shop, amount) tuples in order, which writerows writes directly.

    Python
    import csv
    
    with open("statement.csv", "w", newline="", encoding="utf-8") as f:
        f.write("date;shop;amount\n03-01;Grocer;-23.40\n03-02;Salary;1500.00\n03-02;Cafe;-4.20\n03-04;Grocer;-31.10\n")
    
    spent = {}
    with open("statement.csv", newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f, delimiter=";"):
            amount = float(row["amount"])
            if amount < 0:
                spent[row["shop"]] = round(spent.get(row["shop"], 0) - amount, 2)
    
    with open("summary.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["shop", "spent"])
        writer.writerows(sorted(spent.items()))
    
    with open("summary.csv", newline="", encoding="utf-8") as f:
        for row in csv.reader(f):
            print(row)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Why does my file have blank lines between rows on Windows?

It was opened for writing without newline="". The csv writer adds its own line endings, and Windows text mode then adds another.

Can I open the CSV in a spreadsheet afterwards?

Yes, that is the point of the format. If accented letters look wrong, the spreadsheet guessed the encoding; most have an import option where you choose UTF-8.

What if some rows have missing values?

The reader returns an empty string for an empty cell. Check for it before converting, for example float(row['price']) if row['price'] else 0.0.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 13 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.