Beginner   Chapter 104 · 26 min read · Module 8: File Handling

Working with CSV Files

Learning objectives
  • After this chapter you can explain what a CSV file is and why it is popular.
  • You can read rows with csv.reader and csv.DictReader.
  • You can write rows with csv.writer and csv.DictWriter and use newline="" correctly.
  • You can handle values that contain commas or quotes, and change the delimiter.
  • You can convert text values to numbers and compute totals from a CSV file.

CSV stands for comma separated values. It is a plain text format for tables: each line is a row, and the values in a row are separated by commas. Spreadsheet programs such as Excel and Google Sheets can open and save CSV files, so it is a common way to share data.

You could read a CSV file with split(","), but that breaks as soon as a value itself contains a comma, for example the address "12 Main Road, Pune". Python's built in csv module understands these tricky cases for you.

In this chapter you will read and write CSV files with lists and with dictionaries, change the delimiter, and calculate a total from a table. The csv module is part of the standard library, so there is nothing to install.

What a CSV file looks like

The first line of a CSV file is often a header that names the columns. Every other line is one record. All values are stored as text, even the ones that look like numbers. That is important: when you read the age 21, you get the string "21", and you must convert it with int() if you want to do arithmetic.

Writing with csv.writer

Open the file in write mode and pass the file object to csv.writer(). Then call writerow() for one row or writerows() for many rows. Always open CSV files with newline="". The csv module handles line endings by itself, and without this argument you may get blank lines between rows on Windows.

Example 1: Write a CSV file
import csv

rows = [
    ["name", "age", "city"],
    ["Asha", 21, "Pune"],
    ["Ravi", 25, "Delhi"],
]

with open("people.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f, lineterminator="\n")
    writer.writerows(rows)

with open("people.csv", encoding="utf-8") as f:
    print(f.read(), end="")
name,age,city Asha,21,Pune Ravi,25,Delhi

We set lineterminator="\n" here only so that the printed text is the same on every system. By default the csv module ends each row with \r\n, which every CSV reader accepts.

Reading with csv.reader

The object returned by csv.reader() is an iterator. Each step gives you one row as a list of strings. The first row is the header, unless the file has none. You can get it with next(reader).

Example 2: Read rows
import csv

with open("people.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows([["name", "age"], ["Asha", 21], ["Ravi", 25]])

with open("people.csv", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    header = next(reader)
    print(header)
    for row in reader:
        print(row, type(row[1]).__name__)
['name', 'age'] ['Asha', '21'] str ['Ravi', '25'] str

See that the age is of type str. To use it as a number you write int(row[1]).

Working with dictionaries

Using row positions such as row[2] is easy to get wrong. csv.DictReader reads the header line and then gives every row as a dictionary, so you can write row["city"] instead. In the same way csv.DictWriter writes dictionaries; you give it the list of column names with fieldnames, and call writeheader() once.

Example 3: DictWriter and DictReader
import csv

students = [
    {"name": "Asha", "marks": 82},
    {"name": "Ravi", "marks": 74},
    {"name": "Meena", "marks": 91},
]

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

with open("marks.csv", newline="", encoding="utf-8") as f:
    total = 0
    for row in csv.DictReader(f):
        total += int(row["marks"])
        print(row["name"], row["marks"])

print("average:", total / 3)
Asha 82 Ravi 74 Meena 91 average: 82.33333333333333
Since Python 3.8 DictReader returns normal dictionaries. In older versions it returned OrderedDict objects.

Commas, quotes and other delimiters

What if a value contains a comma? The csv module puts quotes around such a value when writing, and removes them again when reading. If a value contains a quote, the quote is doubled. You do not need to do anything yourself. Some files use another separator, such as a semicolon or a tab. Use the delimiter argument for these, for example csv.reader(f, delimiter=";").

Example 4: Tricky values and a semicolon delimiter
import csv

with open("shops.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f, lineterminator="\n")
    w.writerow(["Blue Cafe", "12 Main Road, Pune"])
    w.writerow(["Book \"Nook\"", "4 Hill Street"])

with open("shops.csv", encoding="utf-8") as f:
    print(f.read(), end="")

with open("shops.csv", newline="", encoding="utf-8") as f:
    for row in csv.reader(f):
        print(row)

with open("semi.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f, delimiter=";", lineterminator="\n").writerow(["a", "b", "c"])
with open("semi.csv", encoding="utf-8") as f:
    print(f.read(), end="")
Blue Cafe,"12 Main Road, Pune" "Book ""Nook""",4 Hill Street ['Blue Cafe', '12 Main Road, Pune'] ['Book "Nook"', '4 Hill Street'] a;b;c

The first line shows quotes around the address because it has a comma. The second shows the doubled quotes. When the rows are read back, the original values return, with no extra quotes.

Why not just use split?

Splitting a line at commas gives the wrong answer for the address above, because it would cut the address into two parts. The csv module also handles values that span several lines, which split cannot do. Use the module whenever the data comes from a spreadsheet or from another person.

Typical workflow

  1. Open the file with newline="" and an encoding.
  2. Create a reader or writer, or the Dict version when the file has a header.
  3. Loop over the rows and convert text to numbers where needed.
  4. Write results to a new file instead of changing the original.

Python syntax

Syntax
import csv
with open("data.csv", newline="", encoding="utf-8") as f:
    for row in csv.reader(f):
        print(row)
Syntax
with open("out.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["a", "b"])
Syntax
with open("data.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"])

Real-world applications

  • Importing and exporting data from spreadsheets.
  • Reading downloaded reports, such as sales or marks lists.
  • Preparing data for charts or for machine learning.
  • Sharing tables between programs written in different languages.

Common mistakes

Mistake: Opening a CSV file without newline="".
Fix: Always pass newline="" so the csv module can handle line endings and you do not get blank rows.
Mistake: Doing arithmetic on values read from a CSV file without converting them.
Fix: Every value is a string. Use int() or float() before adding or comparing.
Mistake: Splitting lines with split(",") by hand.
Fix: Use csv.reader, which understands quotes and commas inside values.
Mistake: Forgetting writeheader() with DictWriter.
Fix: Call writer.writeheader() once before writing the rows.
Mistake: Using the wrong delimiter for files that use semicolons or tabs.
Fix: Pass delimiter=";" or delimiter="\t" to the reader or writer.

Important tips

  • Use DictReader when the file has a header so your code reads like the column names.
  • Check the first rows with print before writing the rest of your program.
  • Wrap int() in try and except when the data may contain bad values.
  • For large analysis work, the pandas package is also popular, but csv is enough for many tasks.

Key points summary

  • CSV is a plain text table format.
  • csv.reader gives lists, csv.DictReader gives dictionaries.
  • Open CSV files with newline="".
  • All values are read as strings.
  • The csv module handles commas and quotes inside values.

Exam and interview points

  • The csv module is in the standard library.
  • writerow takes one row, writerows takes many rows.
  • DictWriter needs fieldnames; DictReader uses the first line as keys.
  • Values are always strings when read.

Quick revision

  • import csv
  • reader gives lists, DictReader gives dicts.
  • Open with newline="".
  • Convert text to numbers yourself.
  • delimiter changes the separator.

Frequently asked questions

Why do I need newline="" when opening a CSV file?

The csv module handles line endings itself. Without it, Windows may write an extra blank line after each row.

Can I read a CSV file into numbers directly?

No. The module returns text. Convert with int() or float(), or use csv.QUOTE_NONNUMERIC for reading float values.

What if the CSV file uses semicolons?

Pass delimiter=";" when you create the reader or writer.

Is the csv module enough for big data?

It works for files of any size because it reads row by row, but for analysis many people use pandas.

Practise this chapter

17 practice questions Take the chapter quiz

Related chapters