Python CSV
Learn how to read, write, update and process
CSV files using Python's built-in
csv module.
Learning Objectives
What you will learn in this lesson
- Understand what CSV files are.
- Understand how rows and columns are represented.
- Use Python's built-in
csvmodule. - Read CSV files using
csv.reader(). - Work with CSV headers.
- Read structured rows using
DictReader. - Create CSV files using
csv.writer(). - Write dictionary-based data using
DictWriter. - Append new records to CSV files.
- Process and analyze CSV data using Python.
What Is CSV?
Understanding comma-separated values
CSV stands for Comma-Separated Values.
A CSV file is a simple text file used to store tabular data in rows and columns.
For example, a student dataset might look like this:
name,age,marks
Ali,20,85
Sara,22,92
Ahmed,21,78
Each line represents a row, while commas separate individual values.
Simple Idea
A CSV file is essentially a simple way of storing table-like information in plain text.
Why CSV Is Important
Where CSV files are used
CSV files are extremely common in business, data analysis and software development.
Common Uses
- Excel exports
- Customer records
- Sales reports
- Employee data
- Product inventories
- Student records
- Marketing data
- Data analysis projects
- Importing and exporting datasets
CSV is particularly useful because almost every spreadsheet application can open CSV files.
Microsoft Excel, Google Sheets and many data-analysis tools can work with CSV files.
CSV Structure
Rows, columns and headers
Consider this CSV file:
name,department,salary
Ali,Sales,60000
Sara,Marketing,75000
Ahmed,IT,90000
The first row is commonly used as the header row.
name | department | salary
---------|------------|-------
Ali | Sales | 60000
Sara | Marketing | 75000
Ahmed | IT | 90000
The header tells us what each column represents.
The csv Module
Python's built-in CSV tools
Python includes a built-in module named
csv.
import csv
No external installation is required. The module is included with Python.
Important CSV Tools
csv.reader()csv.DictReader()csv.writer()csv.DictWriter()
Reading a CSV File
Opening and processing CSV data
The first step is to open the CSV file using
Python's open() function.
import csv
with open("students.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Each row returned by csv.reader()
is represented as a list.
['name', 'age', 'marks']
['Ali', '20', '85']
['Sara', '22', '92']
['Ahmed', '21', '78']
Important
Values read from a CSV file are normally strings. If you need numbers, you may need to convert them.
csv.reader()
Reading rows as lists
csv.reader() is useful when you want
direct access to each row and column by position.
import csv
with open("students.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
next(reader)
for row in reader:
name = row[0]
age = int(row[1])
marks = int(row[2])
print(name, marks)
Ali 85
Sara 92
Ahmed 78
next(reader) skips the header row.
Working with Headers
Understanding the first row
Many CSV files contain a header row. You can capture the header separately.
import csv
with open("students.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
headers = next(reader)
print("Headers:", headers)
for row in reader:
print(row)
Headers: ['name', 'age', 'marks']
['Ali', '20', '85']
['Sara', '22', '92']
['Ahmed', '21', '78']
csv.DictReader()
Reading rows as dictionaries
DictReader makes CSV data easier to
work with because each row becomes a dictionary.
import csv
with open("students.csv", "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for student in reader:
print(student["name"])
print(student["marks"])
Ali
85
Sara
92
Ahmed
78
Why DictReader Is Useful
Instead of remembering that marks are in
column 2, you can simply use
student["marks"].
Writing CSV Files
Creating structured CSV data
Python can also create CSV files.
The basic workflow is:
- Open a file in write mode.
- Create a CSV writer.
- Write the header.
- Write the rows.
- Close the file using
with.
import csv
with open("students.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["name", "age", "marks"])
writer.writerow(["Ali", 20, 85])
writer.writerow(["Sara", 22, 92])
writer.writerow(["Ahmed", 21, 78])
csv.writer()
Writing rows and columns
csv.writer() provides methods for
writing rows into a CSV file.
writerow()
writer.writerow(["Ali", 20, 85])
writerows()
Use writerows() to write multiple rows.
rows = [
["Ali", 20, 85],
["Sara", 22, 92],
["Ahmed", 21, 78]
]
writer.writerows(rows)
csv.DictWriter()
Writing dictionary-based records
DictWriter allows you to write
dictionaries directly into a CSV file.
import csv
fieldnames = ["name", "age", "marks"]
students = [
{"name": "Ali", "age": 20, "marks": 85},
{"name": "Sara", "age": 22, "marks": 92},
{"name": "Ahmed", "age": 21, "marks": 78}
]
with open("students.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(
file,
fieldnames=fieldnames
)
writer.writeheader()
writer.writerows(students)
Professional Approach
DictWriter is often convenient
when your application already stores records
as dictionaries.
Appending CSV Data
Adding new records without replacing existing ones
Use mode "a" when you want to append
new rows to an existing CSV file.
import csv
with open("students.csv", "a", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["Usman", 23, 88])
Be Careful
When using append mode, do not repeatedly write the header unless you intentionally want another header row.
Delimiters
CSV does not always use commas
Although CSV commonly means comma-separated values, files can use other delimiters such as semicolons or tabs.
For example:
name;age;marks
Ali;20;85
Sara;22;92
You can specify the delimiter when reading the file.
import csv
with open("students.csv", "r", encoding="utf-8") as file:
reader = csv.reader(
file,
delimiter=";"
)
for row in reader:
print(row)
Quoting & Special Values
Handling commas and complex text
CSV files may contain text that itself includes commas. Quoting allows the CSV format to distinguish between commas inside a value and commas separating columns.
name,address
Ali,"House 10, Street 5, Multan"
Sara,"House 20, Street 8, Lahore"
Python's csv module handles CSV quoting
rules for you.
import csv
with open("customers.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["name", "address"])
writer.writerow([
"Ali",
"House 10, Street 5, Multan"
])
The newline Parameter
A small detail that matters
When writing CSV files in Python, it is recommended to use:
with open(
"students.csv",
"w",
newline="",
encoding="utf-8"
) as file:
writer = csv.writer(file)
The newline="" setting allows the CSV
module to handle line endings correctly.
Good Habit
Whenever you write CSV files with Python,
remember the combination:
newline="" and
encoding="utf-8".
CSV Encoding
Working with international text
CSV files may contain names, addresses and other information in many languages.
Using UTF-8 encoding helps Python handle a wide range of characters.
with open(
"customers.csv",
"r",
encoding="utf-8"
) as file:
reader = csv.reader(file)
for row in reader:
print(row)
Best Practice
Explicitly specifying
encoding="utf-8" makes your
programs more predictable when working with
international data.
Processing CSV Data
Turning raw CSV rows into useful information
CSV becomes much more powerful when combined with Python's calculations, conditions and loops.
Example — Calculate Average Marks
import csv
total = 0
count = 0
with open("students.csv", "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for student in reader:
marks = int(student["marks"])
total += marks
count += 1
average = total / count
print("Average:", average)
Average: 85.0
Example — Find High Scorers
import csv
with open("students.csv", "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for student in reader:
marks = int(student["marks"])
if marks >= 90:
print(student["name"])
Sara
Real-World Examples
How CSV is used in practical applications
1. Sales Reports
A business might export its sales information into a CSV file:
product,quantity,price
Laptop,5,85000
Mouse,20,2500
Keyboard,12,4500
2. Customer Records
name,email,city
Ali,ali@example.com,Multan
Sara,sara@example.com,Lahore
Ahmed,ahmed@example.com,Islamabad
3. Data Analysis
Analysts frequently receive datasets as CSV files. Python can read these files and calculate totals, averages, filter records and generate reports.
Your Future Lessons
Later in PyLearn, you will learn NumPy, Pandas and data analysis techniques that make large CSV datasets much easier to process.
Common CSV Mistakes
Problems beginners often encounter
1. Forgetting to import csv
import csv
2. Using the wrong file mode
Use "r" for reading,
"w" for replacing/writing,
and "a" for appending.
3. Forgetting newline=""
When writing CSV files, use:
open("data.csv", "w", newline="", encoding="utf-8")
4. Forgetting that CSV values are strings
age = int(row["age"])
salary = float(row["salary"])
5. Accidentally writing the header repeatedly
Be careful when using append mode. Headers normally belong only at the top of the file.
6. Assuming every CSV uses commas
Some files use semicolons, tabs or other delimiters.
Practice Exercises
Strengthen your CSV skills
Exercise 1 — Read a CSV
Create a CSV file containing five students
and print every row using csv.reader().
Exercise 2 — Skip the Header
Read a CSV file and use next()
to skip its header.
Exercise 3 — Use DictReader
Read a student CSV file using
csv.DictReader() and print
each student's name.
Exercise 4 — Create a CSV
Create an employee CSV containing name, department and salary.
Exercise 5 — Append Data
Add a new employee to the existing CSV without deleting previous records.
Exercise 6 — Calculate Total
Read a sales CSV and calculate total revenue.
Exercise 7 — Find High Salaries
Read an employee CSV and display employees whose salary is greater than 100,000.
Exercise 8 — DictWriter
Create a CSV file using
csv.DictWriter().
Mini Challenge — Sales Report Analyzer
Build a practical CSV-based application
Build a small Python program that reads sales information from a CSV file and generates a report.
Your Program Should
- Create a
sales.csvfile. - Store product, quantity and price.
- Read the file using
DictReader. - Calculate revenue for each product.
- Calculate total revenue.
- Find the product with the highest revenue.
- Count the total number of products sold.
- Display a professional summary.
Suggested CSV
product,quantity,price
Laptop,5,85000
Mouse,20,2500
Keyboard,12,4500
Monitor,4,35000
Expected Report
===== SALES REPORT =====
Total Units Sold: 41
Total Revenue: 618000
Top Product:
Laptop
=========================
Challenge Goal
This challenge combines CSV reading, dictionary access, loops, type conversion, calculations and conditional logic.
Quick Knowledge Check
Test what you learned
1. What does CSV stand for?
2. Which Python module is used for CSV files?
3. What does csv.reader() return for each row?
4. Which class reads CSV rows as dictionaries?
5. Which function writes one row to a CSV file?
6. Which mode is normally used to append data?
7. What does DictWriter work with?
8. Why is newline="" commonly used when writing CSV files?
9. What type are CSV values usually read as?
10. Which parameter can specify a semicolon instead of a comma?
Lesson Summary
What you should remember
Key Takeaways
- CSV stands for Comma-Separated Values.
- CSV files store tabular information in rows and columns.
-
Python provides the built-in
csvmodule. -
csv.reader()reads rows as lists. -
csv.DictReader()reads rows as dictionaries. -
csv.writer()writes rows to CSV files. -
csv.DictWriter()writes dictionary-based records. -
Use
"a"mode to append new records. - CSV values are normally read as strings and may need conversion.
-
The
delimitercan be changed when a CSV uses something other than commas. -
newline=""is recommended when writing CSV files. - CSV is widely used for business reports, customer data and data analysis.
You now have the skills to create, read and process practical CSV datasets using Python.
Excellent work!
You've completed Python CSV. Mark this lesson complete and continue your journey.