Lesson 16 of 208 min read
CSV File Handling in Python
Prerequisites: Text file handling, lists, basic file modes
1. What is CSV?
- CSV stands for Comma Separated Values., A CSV file stores tabular data (rows and columns) as plain text., Each line is a row (record), and values within a row are separated by commas., CSV files can be opened in spreadsheet applications (Excel, Google Sheets) or any text editor.
Example CSV Content (students.csv)
RollNo,Name,Marks
101,Aman,85
102,Priya,92
103,Rahul,78
2. The csv Module
Python's built-in csv module provides functions to read and write CSV files.
import csv
3. Opening CSV Files
Why newline=''?
When opening CSV files for writing, always use newline="" to prevent extra blank lines on Windows.
# Writing - use newline=""
f = open("data.csv", "w", newline="")
# Reading - newline="" is optional but recommended
f = open("data.csv", "r")
Without newline="", Windows adds an extra \r\n resulting in blank rows between data rows.
4. Writing CSV Files
csv.writer, Create a Writer Object
import csv
f = open("data.csv", "w", newline="")
writer = csv.writer(f)
writerow, Write a Single Row
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["RollNo", "Name", "Marks"]) # Header row
writer.writerow([101, "Aman", 85]) # Data row
writer.writerow([102, "Priya", 92])
print("Data written to data.csv")
# data.csv contents:
# RollNo,Name,Marks
# 101,Aman,85
# 102,Priya,92
writerows, Write Multiple Rows at Once
import csv
header = ["RollNo", "Name", "Marks"]
data = [
[101, "Aman", 85],
[102, "Priya", 92],
[103, "Rahul", 78],
[104, "Sneha", 95]
]
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(header) # Write header
writer.writerows(data) # Write all data rows at once
print("Multiple rows written to data.csv")
# data.csv contents:
# RollNo,Name,Marks
# 101,Aman,85
# 102,Priya,92
# 103,Rahul,78
# 104,Sneha,95
5. Reading CSV Files
csv.reader, Create a Reader Object
import csv
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# Output:
# ['RollNo', 'Name', 'Marks']
# ['101', 'Aman', '85']
# ['102', 'Priya', '92']
# ['103', 'Rahul', '78']
# ['104', 'Sneha', '95']
Note: Every value is read as a string. Numbers must be explicitly converted using int or float.
Skipping the Header Row
import csv
with open("data.csv", "r") as f:
reader = csv.reader(f)
header = next(reader) # Read and skip header
print("Columns:", header)
for row in reader:
print(f"Roll: {row[0]}, Name: {row[1]}, Marks: {row[2]}")
# Output:
# Columns: ['RollNo', 'Name', 'Marks']
# Roll: 101, Name: Aman, Marks: 85
# Roll: 102, Name: Priya, Marks: 92
# Roll: 103, Name: Rahul, Marks: 78
# Roll: 104, Name: Sneha, Marks: 95
Formatted Display
import csv
with open("data.csv", "r") as f:
reader = csv.reader(f)
header = next(reader)
print(f"{header[0]:<10}{header[1]:<15}{header[2]:<10}")
print("-" * 35)
for row in reader:
print(f"{row[0]:<10}{row[1]:<15}{row[2]:<10}")
# Output:
# RollNo Name Marks
# -----------------------------------
# 101 Aman 85
# 102 Priya 92
# 103 Rahul 78
# 104 Sneha 95
6. DictReader and DictWriter (Brief)
csv.DictWriter, Write Using Dictionaries
import csv
fieldnames = ["RollNo", "Name", "Marks"]
with open("dict_data.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader
writer.writerow({"RollNo": 101, "Name": "Aman", "Marks": 85})
writer.writerow({"RollNo": 102, "Name": "Priya", "Marks": 92})
# dict_data.csv contents:
# RollNo,Name,Marks
# 101,Aman,85
# 102,Priya,92
csv.DictReader, Read as Dictionaries
import csv
with open("dict_data.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"Roll: {row['RollNo']}, Name: {row['Name']}, Marks: {row['Marks']}")
# Output:
# Roll: 101, Name: Aman, Marks: 85
# Roll: 102, Name: Priya, Marks: 92
Advantage: You access values by column name instead of index, more readable and less error-prone.
Practice Programs
Program 1: Create CSV with Headers and Data
import csv
header = ["Name", "Class", "Section", "Marks"]
students = [
["Aman", "XII", "A", 85],
["Priya", "XII", "B", 92],
["Rahul", "XII", "A", 78],
["Sneha", "XII", "C", 95],
["Vikram", "XII", "B", 88]
]
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(students)
print("CSV file 'students.csv' created successfully!")
print(f"Total records written: {len(students)}")
# Output:
# CSV file 'students.csv' created successfully!
# Total records written: 5
# students.csv contents:
# Name,Class,Section,Marks
# Aman,XII,A,85
# Priya,XII,B,92
# Rahul,XII,A,78
# Sneha,XII,C,95
# Vikram,XII,B,88
Program 2: Read CSV and Display
import csv
print("Student Data:")
print("=" * 50)
print(f"{'Name':<12}{'Class':<8}{'Section':<10}{'Marks':<8}")
print("=" * 50)
with open("students.csv", "r") as f:
reader = csv.reader(f)
next(reader) # Skip header
for row in reader:
print(f"{row[0]:<12}{row[1]:<8}{row[2]:<10}{row[3]:<8}")
print("=" * 50)
# Output:
# Student Data:
# ==================================================
# Name Class Section Marks
# ==================================================
# Aman XII A 85
# Priya XII B 92
# Rahul XII A 78
# Sneha XII C 95
# Vikram XII B 88
# ==================================================
Program 3: Create CSV with User-ID and Password
import csv
with open("users.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["UserID", "Password"])
n = int(input("How many users to register? "))
for i in range(n):
print(f"\nUser {i+1}:")
uid = input(" Enter User ID: ")
pwd = input(" Enter Password: ")
writer.writerow([uid, pwd])
print("\nUser data saved to users.csv")
# Test Run:
# How many users to register? 3
#
# User 1:
# Enter User ID: admin
# Enter Password: admin123
#
# User 2:
# Enter User ID: student1
# Enter Password: pass456
#
# User 3:
# Enter User ID: teacher
# Enter Password: teach789
#
# User data saved to users.csv
# users.csv:
# UserID,Password
# admin,admin123
# student1,pass456
# teacher,teach789
Program 4: Search Password for Given User-ID
import csv
search_id = input("Enter User ID to search: ")
found = False
with open("users.csv", "r") as f:
reader = csv.reader(f)
next(reader) # Skip header
for row in reader:
if row[0] == search_id:
print(f"Password for '{search_id}': {row[1]}")
found = True
break
if not found:
print(f"User ID '{search_id}' not found.")
# Test Run 1:
# Enter User ID to search: student1
# Password for 'student1': pass456
# Test Run 2:
# Enter User ID to search: unknown
# User ID 'unknown' not found.
Program 5: Add New Records to Existing CSV
import csv
n = int(input("How many records to add? "))
with open("students.csv", "a", newline="") as f:
writer = csv.writer(f)
for i in range(n):
print(f"\nStudent {i+1}:")
name = input(" Name: ")
cls = input(" Class: ")
sec = input(" Section: ")
marks = input(" Marks: ")
writer.writerow([name, cls, sec, marks])
print(f"\n{n} record(s) added to students.csv")
# Test Run:
# How many records to add? 2
#
# Student 1:
# Name: Kavya
# Class: XII
# Section: A
# Marks: 91
#
# Student 2:
# Name: Rohan
# Class: XII
# Section: C
# Marks: 82
#
# 2 record(s) added to students.csv
Program 6: Count Records in CSV
import csv
with open("students.csv", "r") as f:
reader = csv.reader(f)
header = next(reader) # Skip header
count = 0
total_marks = 0
for row in reader:
count += 1
total_marks += int(row[3])
print(f"Total records : {count}")
print(f"Total marks : {total_marks}")
if count > 0:
print(f"Average marks : {total_marks / count:.2f}")
# Output:
# Total records : 7
# Total marks : 611
# Average marks : 87.29
Quick Reference: csv Module Functions
| Function | Purpose | Example |
|---|---|---|
csv.writer(file) |
Create writer object | w = csv.writer(f) |
writer.writerow(list) |
Write one row | w.writerow([1, "A", 90]) |
writer.writerows(list_of_lists) |
Write multiple rows | w.writerows(data) |
csv.reader(file) |
Create reader object | r = csv.reader(f) |
next(reader) |
Read/skip one row | header = next(r) |
csv.DictWriter(file, fieldnames) |
Dict-based writer | w = csv.DictWriter(f, fields) |
writer.writeheader |
Write header from fieldnames | w.writeheader |
csv.DictReader(file) |
Dict-based reader | r = csv.DictReader(f) |
Common Mistakes
| Mistake | Correct Approach |
|---|---|
Forgetting newline="" when writing |
Always use open("file.csv", "w", newline="") |
Forgetting import csv |
Must import before using csv.reader or csv.writer |
| Treating CSV values as numbers | csv.reader returns everything as strings, convert with int or float |
Using pickle.dump/load for CSV |
CSV uses csv.writer/reader, not pickle |
Using writerow with a string instead of list |
writerow("Hello") writes H,e,l,l,o - always pass a list |
Opening with "w" to add records |
Use "a" (append) mode to add to existing file |
$1$2 Quick Tips
- csv vs pickle: CSV stores tabular text data; pickle stores Python objects in binary format. Know the differences.
- writerow vs writerows:
writerowwrites ONE row (a list),writerowswrites MULTIPLE rows (a list of lists). - newline="" is a frequently asked MCQ, know why it is used (prevents extra blank lines).
- csv.reader returns strings - remember to convert to int/float when needed.
- next(reader) is the standard way to skip the header, commonly tested.
- Code writing questions typically ask: create a CSV, read a CSV, or search in a CSV.
- Delimiter: By default, the delimiter is a comma. You can change it:
writer = csv.writer(f, delimiter="\t") # Tab-separated
reader = csv.reader(f, delimiter="|") # Pipe-separated
- Remember the correct opening patterns:
- Write:
open("file.csv", "w", newline="") - Read:
open("file.csv", "r") - Append:
open("file.csv", "a", newline="")
Prefer watching over reading?
Subscribe for free.