Working with CSV files
Read and write spreadsheet-style data with the csv module.
🎬 Video version coming soon — read it now
CSV (comma-separated values) is the simplest spreadsheet format. Excel and Google Sheets can save as CSV, and almost every system can export it.
name,branch,cgpa
Anil,CSE,8.4
Bhavana,ECE,9.1The first row is usually the header: the column names.
Writing a CSV
import csv
students = [
{"name": "Anil", "branch": "CSE", "cgpa": 8.4},
{"name": "Bhavana", "branch": "ECE", "cgpa": 9.1},
{"name": "Chaitanya", "branch": "IT", "cgpa": 7.2},
]
with open("students.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "branch", "cgpa"])
writer.writeheader()
writer.writerows(students)newline="" prevents blank lines between rows on Windows. Double-click the file in Colab's file panel to see it.
Reading a CSV
import csv
with open("students.csv", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
for r in rows:
print(r["name"], r["cgpa"])DictReader gives you exactly the list of dictionaries shape from the Lists, Dicts & Data course.
Everything comes back as text
print(type(rows[0]["cgpa"])) # <class 'str'>CSV stores only text, so convert numbers yourself:
for r in rows:
r["cgpa"] = float(r["cgpa"])
avg = sum(r["cgpa"] for r in rows) / len(rows)
print(f"Average CGPA: {avg:.2f}")Why use the csv module instead of split(",")?
Real data has commas inside values: "Rao, K.",CSE,8.1. The csv module handles the quotes correctly; a plain split(",") breaks the row into the wrong pieces.
Uploading your own CSV to Colab
Click the folder icon → upload button, or:
from google.colab import files
uploaded = files.upload()pd.read_csv) in the Python for AI course. The csv module is perfect for simple scripts and has nothing to install.In one line
csv.DictWriter writes rows of dictionaries, csv.DictReader reads them back, and every value comes back as text.
Share with a friend