Skip to content
Hands-on Mentor
ENTR
Back to blog

How to read a CSV file in Python with the csv module

Read a CSV file in Python with the built-in csv module: reader, DictReader, totals, writing a new file, semicolon delimiters and encoding. Nothing to install.

5 min read

To read a CSV file in Python, open it with open() and pass the file to csv.reader or csv.DictReader from the built-in csv module. csv.reader gives each row as a list, and csv.DictReader gives each row as a dictionary with the column names as keys. Every value arrives as a string, so convert numbers yourself.

What does a CSV file look like?

CSV means comma-separated values. It stores a table as plain text. This is the order file of Corner Café, a small café in the port city of Port Alder, owned by Ada:

order_id,item,quantity,unit_price,payment
1,latte,2,4.25,card
2,tea,3,1.25,cash
3,brownie,1,3.75,card
4,latte,1,4.25,cash
5,lemonade,2,3.25,card
6,water,4,0.75,cash

The first line holds the column names. Every other line is one record. To follow along anywhere, let's create the file with Python first:

text = """order_id,item,quantity,unit_price,payment
1,latte,2,4.25,card
2,tea,3,1.25,cash
3,brownie,1,3.75,card
4,latte,1,4.25,cash
5,lemonade,2,3.25,card
6,water,4,0.75,cash
"""
with open("orders.csv", "w", encoding="utf-8", newline="") as f:
    f.write(text)

How do you read a CSV file with csv.reader?

import csv

with open("orders.csv", encoding="utf-8", newline="") as f:
    reader = csv.reader(f)
    header = next(reader)
    for row in reader:
        print(row)
['1', 'latte', '2', '4.25', 'card']
['2', 'tea', '3', '1.25', 'cash']
['3', 'brownie', '1', '3.75', 'card']
['4', 'latte', '1', '4.25', 'cash']
['5', 'lemonade', '2', '3.25', 'card']
['6', 'water', '4', '0.75', 'cash']

next(reader) takes the header line out of the loop. Look at the values: '2' is a string, not a number. The newline="" argument lets the csv module handle line endings. The Python documentation recommends it for reading and for writing.

How do you read a CSV file as dictionaries?

Use csv.DictReader. It reads the header itself and lets you reach each column by name. Let's total the revenue:

import csv

total = 0
with open("orders.csv", encoding="utf-8", newline="") as f:
    for row in csv.DictReader(f):
        amount = int(row["quantity"]) * float(row["unit_price"])
        total += amount
        print(f"{row['item']}: ${amount:.2f}")
print(f"Total revenue: ${total:.2f}")
latte: $8.50
tea: $3.75
brownie: $3.75
latte: $4.25
lemonade: $6.50
water: $3.00
Total revenue: $29.75

Each row looks like {"order_id": "1", "item": "latte", ...}. Your code stays readable and keeps working if the column order changes. Convert with int() or float() before you calculate.

How do you write a CSV file in Python?

import csv

summary = [
    {"item": "latte", "revenue": 12.75},
    {"item": "tea", "revenue": 3.75},
    {"item": "brownie", "revenue": 3.75},
]

with open("summary.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["item", "revenue"])
    writer.writeheader()
    writer.writerows(summary)

with open("summary.csv", encoding="utf-8") as f:
    print(f.read())
item,revenue
latte,12.75
tea,3.75
brownie,3.75
  • "w" opens the file for writing. It erases a file with the same name.
  • writeheader() writes the column names.
  • writerows() writes all records.

Why is split(",") not enough?

A field can contain a comma. Then the value is wrapped in double quotes:

import csv

line = '7,"Latte, large",1,4.75,card'
print(line.split(","))
print(next(csv.reader([line])))
['7', '"Latte', ' large"', '1', '4.75', 'card']
['7', 'Latte, large', '1', '4.75', 'card']

split cuts at every comma and returns six pieces. The csv module understands the quotes and returns five fields. Use it whenever real data might contain text.

How do you read a CSV file with a semicolon delimiter?

Some programs separate columns with a semicolon, especially in regions where the comma is the decimal mark. Tell the reader with delimiter:

import csv

with open("semicolon.csv", "w", encoding="utf-8") as f:
    f.write("item;quantity\ntea;3\nlatte;1\n")

with open("semicolon.csv", encoding="utf-8", newline="") as f:
    for row in csv.reader(f, delimiter=";"):
        print(row)
['item', 'quantity']
['tea', '3']
['latte', '1']

Some spreadsheet exports start with an invisible marker, and the first column name then looks like 'order_id'. Open the file with encoding="utf-8-sig" to remove it. Before you work with a new CSV, print its first few lines and check the delimiter and the headers.

Can you read a CSV file with pandas instead?

Yes. pandas.read_csv("orders.csv") loads the whole table into a DataFrame and converts numbers for you. It is the better tool for large tables and analysis. The csv module is the right start because it needs no installation and shows you what a CSV file really is.

Common mistakes

  • Broken characters: pass encoding="utf-8" when you open the file.
  • Everything in one column: the delimiter may not be a comma. Try delimiter=";".
  • Math on strings: "3" * "1.25" raises a TypeError. Convert first.
  • Treating the header as data: with reader, skip the first row using next().
  • Leaving the file open: with open(...) closes the file for you.

What to read next

  • Build a reader for a broken file step by step in the lesson [CSV files](/learn/python/csv).
  • Practice string formatting for reports with [Python f-strings](/blog/python-f-strings).
  • See all lessons in the [Python course](/courses/python).
  • #python
  • #csv
  • #files
  • #data
All posts