← Back to Python Course | Chapter 9: File Handling | Lesson 4 of 6

Python CSV Files

A CSV file is a simple table saved as text, with each row on a line and columns separated by commas, like a spreadsheet in its simplest form. Python's csv tools read and write these easily.
Syntax
python
import csv

with open("file.csv", newline="") as file:
    for row in csv.reader(file):
        # row is a list

The csv Module

CSV (Comma-Separated Values) is a plain-text format for tabular data, and Python's built-in csv module handles the tricky edge cases (commas inside quoted fields, escaped quotes) that make manually splitting on ',' unreliable for real-world CSV files.

Example: The csv Module

python
import csv
with open("data.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "age"])
    writer.writerow(["Alex, Jr.", 30])  # comma inside the value is handled correctly
print("CSV module handles commas inside quoted fields")

Reading CSV Files

csv.reader wraps an open file and yields each row as a list of string values, automatically handling quoted fields correctly -- you typically loop over the reader object directly to process the file one row at a time.

Example: Reading CSV Files

python
import csv
with open("data.csv", "w", newline="") as f:
    csv.writer(f).writerow(["Alex", "30"])
with open("data.csv", "r", newline="") as f:
    for row in csv.reader(f):  # each row comes back as a list of strings
        print(row)

Writing CSV Files

csv.writer wraps an open file (opened in write mode) and its .writerow() method correctly quotes fields containing commas or special characters for you, so you don't have to manually escape anything yourself.

Example: Writing CSV Files

python
import csv
with open("data.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "age"])  # header row
    writer.writerow(["Alex", 30])  # data row, values quoted/escaped automatically
with open("data.csv") as f:
    print(f.read())

DictReader and DictWriter

csv.DictReader turns each row into a dictionary keyed by the column headers instead of a plain list, so you can write row[email] instead of row[3] -- DictWriter does the reverse, letting you write rows from dictionaries.

Example: DictReader and DictWriter

python
import csv
with open("data.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "email"])
    writer.writeheader()
    writer.writerow({"name": "Alex", "email": "[email protected]"})
with open("data.csv", newline="") as f:
    for row in csv.DictReader(f):  # each row comes back as a dict keyed by header
        print(row["email"])

Handling Delimiters

Not every CSV-like file actually uses commas -- some use tabs or semicolons -- and both csv.reader and csv.writer accept a delimiter parameter to handle those variants without you having to write custom parsing logic.

Example: Handling Delimiters

python
import csv
with open("data.csv", "w", newline="") as f:
    writer = csv.writer(f, delimiter=";")  # use ; instead of , as the separator
    writer.writerow(["name", "age"])
with open("data.csv", newline="") as f:
    for row in csv.reader(f, delimiter=";"):
        print(row)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Opening a CSV file without newline="", which can produce blank lines between rows on Windows.
  2. Splitting lines with line.split(",") instead of the csv module, which breaks on quoted fields containing commas.
  3. Forgetting that every value read is a string, so row[1] + 1 fails until you convert with int().
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.