Working with CSV Files
Working with CSV Files
Some files store data in rows and columns.
This is common for:
- Reports
- Student scores
- Product lists
- Sales data
- Spreadsheets
A popular format for this is CSV.
What Is a CSV File?
CSV means Comma-Separated Values.
Values are separated by commas.
Example file: students.csv
name,score
Tom,85
Sara,92
Ali,70
Each line is one row.
Why CSV Files Matter
CSV files are useful because they:
- Organize data clearly
- Work with spreadsheet apps
- Are easy to share
- Are great for reports
Import the csv Module
Python has a built-in module called csv.
import csv
Reading a CSV File
import csv
with open("students.csv") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output
['name', 'score']
['Tom', '85']
['Sara', '92']
['Ali', '70']
Each row becomes a list.
Skip the Header Row
The first row often contains column names.
import csv
with open("students.csv") as file:
reader = csv.reader(file)
next(reader)
for row in reader:
print(row)
Output
['Tom', '85']
['Sara', '92']
['Ali', '70']
Using DictReader
DictReader uses column names as keys.
import csv
with open("students.csv") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["name"], row["score"])
Output
Tom 85
Sara 92
Ali 70
Writing a CSV File
Use csv.writer().
import csv
with open("products.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["name", "price"])
writer.writerow(["Book", 10])
writer.writerow(["Pen", 2])
File Content
name,price
Book,10
Pen,2
Appending Rows
import csv
with open("products.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Bag", 25])
Updated File
name,price
Book,10
Pen,2
Bag,25
Why newline=""?
It helps avoid blank lines on some systems.
Common Beginner Errors
Forgetting import csv
The code will not work.
Wrong File Name
Check spelling carefully.
Forgetting newline=""
May create extra blank lines.
Code Along
Create cities.csv with:
city,country
Toronto,Canada
New York,USA
Then read and print all rows.
Mini Challenge
Build a score saver.
Steps:
- Create
scores.csv - Add header:
name,score
- Add 3 student rows
- Read the file
- Print each student name and score
Expected output:
Tom 85
Sara 92
Ali 70
Real World Use Case
Programs use CSV files for exports, reports, backups, spreadsheets, and data sharing.
Quiz
- What does CSV mean?
- How is data separated in CSV?
- What does
DictReaderdo? - Why use
newline=""when writing?
Assignment
Create a books.csv file with title and price columns. Add 3 books, then read and print them.
Summary
You learned how to read CSV files, skip headers, use DictReader, write rows, and store table-style data in Python.