Introduction
CSV (Comma-Separated Values) files are one of the most commonly used file formats for storing and exchanging data. They are simple, lightweight, and supported by many applications, including spreadsheet software like Microsoft Excel and Google Sheets.
In Python, CSV file handling allows developers to read, write, update, and process tabular data efficiently. CSV files are widely used in data analysis, business applications, reporting systems, and data migration projects because they are easy to create and understand.
Python provides a built-in csv module that simplifies working with CSV files. Instead of manually parsing comma-separated values, developers can use dedicated functions to read and write data accurately.
What is Python CSV File Handling?
Python CSV File Handling refers to the process of reading, writing, and managing CSV (Comma-Separated Values) files using Python.
A CSV file stores data in rows and columns where each value is separated by a comma.
Example CSV File:
Name,Age,City
John,25,New York
Alice,30,London
David,28,Sydney
In Python, the built-in csv module provides tools for:
- Reading CSV files
- Writing CSV files
- Appending records
- Reading rows as dictionaries
- Handling large datasets
Importing the CSV Module
Before working with CSV files, import the csv module.
import csv
The csv module contains functions and classes for handling CSV data efficiently.
Syntax
Reading a CSV File
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Writing a CSV File
import csv
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
Reading CSV Files
The csv.reader() function is used to read CSV files.
Example:
CSV File:
Name,Age
John,25
Alice,30
David,28
Python Code:
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output:
[‘John’, ’25’]
[‘Alice’, ’30’]
[‘David’, ’28’]
Each row is returned as a list.
Accessing Individual Columns
You can access specific values using indexes.
Example:
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
next(reader)
for row in reader:
print(row[0])
Output:
Alice
David
Here:
- row[0] → Name
- row[1] → Age
Skipping the Header Row
Many CSV files contain headers.
Example:
Name,Age
John,25
Alice,30
To skip the header:
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
next(reader)
for row in reader:
print(row)
Output:
[‘Alice’, ’30’]
Writing CSV Files
The csv.writer() function is used to create and write CSV files.
Example:
import csv
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["John", 25])
writer.writerow(["Alice", 30])
Output CSV:
John,25
Alice,30
Writing Multiple Rows
The writerows() method writes multiple rows at once.
Example:
import csv
data = [
["Name", "Age"],
["John", 25],
["Alice", 30],
["David", 28]
]
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
Output:
John,25
Alice,30
David,28
Appending Data to a CSV File
Use append mode (a) to add records.
Example:
import csv
with open("students.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Robert", 27])
Updated CSV:
John,25
Alice,30
David,28
Robert,27
Using DictReader
DictReader reads rows as dictionaries.
Example:
CSV File:
Name,Age
John,25
Alice,30
Code:
import csv
with open("students.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
Output:
{‘Name’: ‘Alice’, ‘Age’: ’30’}
This approach improves readability.
Using DictWriter
DictWriter writes dictionary data to CSV files.
Example:
import csv
with open("students.csv", "w", newline="") as file:
fields = ["Name", "Age"]
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader()
writer.writerow({
"Name": "John",
"Age": 25
})
Output:
John,25
Example
Suppose you want to store employee information.
import csv
with open("employees.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["ID", "Name", "Department"])
writer.writerow([101, "John", "IT"])
writer.writerow([102, "Alice", "HR"])
Output:
101,John,IT
102,Alice,HR
Real-life Example
Imagine you are developing a student management system.
Each student’s information is stored in a CSV file.
import csv
name = input("Enter Name: ")
age = input("Enter Age: ")
with open("students.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow([name, age])
print("Student saved successfully")
Input:
Rahul
20
Output CSV:
Common Mistakes
1. Forgetting to Import csv Module
Incorrect:
reader = csv.reader(file)
Output:
Correct:
import csv
2. Forgetting newline=””
Incorrect:
with open("data.csv", "w") as file:
This may create blank lines on some systems.
Correct:
with open(
"data.csv",
"w",
newline=""
) as file:
3. Using Write Mode Instead of Append Mode
Incorrect:
open("students.csv", "w")
This removes existing data.
Correct:
open("students.csv", "a")
4. Not Skipping Headers
Incorrect:
for row in reader:
print(row)
Headers may be processed as data.
Correct:
next(reader)
Skip the header when needed.
5. Not Using Exception Handling
Incorrect:
with open("data.csv") as file:
Correct:
try:
with open("data.csv") as file:
pass
except FileNotFoundError:
print("File not found")
Best Practices
1. Use the with Statement
with open("data.csv") as file:
pass
Automatically closes files.
2. Use DictReader for Better Readability
csv.DictReader(file)
Makes code easier to understand.
3. Handle Exceptions
try:
pass
except:
pass
Prevents application crashes.
4. Validate Data Before Writing
Check user input before storing it.
5. Keep Consistent Headers
Example:
Name,Age,City
Consistent structure improves maintainability.
Conclusion
Python CSV File Handling is an essential skill for developers who work with structured data. The built-in csv module makes it easy to read, write, append, and process CSV files efficiently. Functions such as csv.reader(), csv.writer(), DictReader, and DictWriter provide flexible ways to manage tabular data.
CSV files are widely used in business applications, educational systems, reporting tools, data analysis projects, and inventory management systems.
Python CSV File Handling – Interview Questions
Q 1: How do you read CSV files in Python?
Q 2: How do you write CSV files in Python?
Q 3: What delimiter is used in CSV files?
Q 4: Can you specify a custom delimiter?
Q 5: Is the CSV module built-in in Python?
Python CSV File Handling – Objective Questions (MCQs)
Q1. Which module is used for CSV file operations in Python?
Q2. Which method reads a CSV file as rows?
Q3. Which method writes a list of rows to a CSV file?
Q4. Which argument is commonly used to prevent extra blank lines when writing CSV?
Q5. What does DictReader in the CSV module do?