Python Tutorial › File Handling › Read/Write CSV

Python Read/Write CSV

BeginnerLesson 43 of 4710 min read7 runnable examples

CSV (comma-separated values) files are plain-text tables that every spreadsheet and database can export. Python’s built-in csv module reads and writes them correctly, including the tricky cases such as commas inside quoted values.

Advertisement
In this lesson
  • Write rows with csv.writer
  • Read rows with csv.reader
  • Use column names with DictReader and DictWriter
  • Summarise CSV data

Write a CSV file

Open the file with newline="" (the csv module handles line endings itself), then write rows as lists.

Python
import csv rows = [    ["name", "city", "score"],    ["Asha", "Pune", 91],    ["Ravi", "Delhi", 78],    ["Meena", "Mumbai, MH", 85],]with open("students.csv", "w", newline="", encoding="utf-8") as f:    writer = csv.writer(f)    writer.writerows(rows) print(open("students.csv", encoding="utf-8").read())
Output
name,city,score
Asha,Pune,91
Ravi,Delhi,78
Meena,"Mumbai, MH",85

Notice that "Mumbai, MH" was wrapped in quotes automatically, because it contains a comma.

Watch out

Without newline="", files written on Windows get an extra blank line between rows.

Read a CSV file

csv.reader returns each row as a list of strings:

Python
import csv with open("students.csv", newline="", encoding="utf-8") as f:    reader = csv.reader(f)    header = next(reader)            # first row    print(header)    for row in reader:        print(row)
Output
['name', 'city', 'score']
['Asha', 'Pune', '91']
['Ravi', 'Delhi', '78']
['Meena', 'Mumbai, MH', '85']

DictReader: rows as dictionaries

DictReader uses the header row as keys, so you can write row["score"] instead of row[2]:

Python
import csv with open("students.csv", newline="", encoding="utf-8") as f:    for row in csv.DictReader(f):        print(row["name"], "scored", row["score"])
Output
Asha scored 91
Ravi scored 78
Meena scored 85

DictWriter

Python
import csv results = [    {"test": "login", "status": "pass", "ms": 812},    {"test": "search", "status": "fail", "ms": 1530},]with open("results.csv", "w", newline="", encoding="utf-8") as f:    writer = csv.DictWriter(f, fieldnames=["test", "status", "ms"])    writer.writeheader()    writer.writerows(results) print(open("results.csv", encoding="utf-8").read().strip())
Output
test,status,ms
login,pass,812
search,fail,1530

Append rows

Python
import csv with open("results.csv", "a", newline="", encoding="utf-8") as f:    csv.writer(f).writerow(["checkout", "pass", 990]) with open("results.csv", newline="", encoding="utf-8") as f:    print(sum(1 for _ in csv.DictReader(f)), "data rows")
Output
3 data rows

Summarise CSV data

Values come back as strings, so convert them before doing maths:

Python
import csv with open("students.csv", newline="", encoding="utf-8") as f:    students = list(csv.DictReader(f)) scores = [int(s["score"]) for s in students]top = max(students, key=lambda s: int(s["score"]))print("Average:", round(sum(scores) / len(scores), 2))print("Top:", top["name"], top["score"])print("Above 80:", [s["name"] for s in students if int(s["score"]) > 80])
Output
Average: 84.67
Top: Asha 91
Above 80: ['Asha', 'Meena']

Other delimiters

Some files use ; or tabs. Pass delimiter:

Python
import csv, io data = "id;product;price\n1;Pen;10\n2;Bag;650\n"for row in csv.DictReader(io.StringIO(data), delimiter=";"):    print(row)
Output
{'id': '1', 'product': 'Pen', 'price': '10'}
{'id': '2', 'product': 'Bag', 'price': '650'}

io.StringIO turns a string into a file-like object, which is handy for testing CSV code without a real file.

Tip

For large data or heavy analysis, Pandas reads CSV in one line: pd.read_csv("students.csv"). See the Pandas lesson.

Check your understanding

Predict the output

import csv, iorows = list(csv.reader(io.StringIO('a,"b,c",d\n1,2,3\n')))print(rows, len(rows[0]))

Quick quiz

1. What type are the values csv.reader returns?

2. Why open CSV files with newline=""?

3. Which class gives each row as a dictionary keyed by the header?

Exercise: filter rows into a new file

From students.csv, write the students who scored at least 80 to toppers.csv with the same header, then print the new file.

Input
students.csv from this lesson
Expected output
name,city,score
Asha,Pune,91
Meena,"Mumbai, MH",85
Hint 1

Use DictReader to read and DictWriter with reader.fieldnames to write.

Program Practice

Python CSV FAQ

How do I read a CSV file in Python?

with open("file.csv", newline="", encoding="utf-8") as f: then for row in csv.reader(f): or csv.DictReader(f) for dictionaries.

How do I skip the header row?

Call next(reader) once before the loop, or use DictReader, which consumes the header for you.

Why do I get blank lines between rows in my CSV on Windows?

The file was opened without newline="". Add it to open() when writing CSV files.

Should I use csv or pandas?

Use csv for simple reading and writing with no extra installs. Use pandas when you need filtering, grouping, statistics or Excel export.

1 thought on “Python Read/Write CSV”

Leave a Comment