π Quick Info
- Topic: Working with CSV files in Python
- Target Audience: Beginners who know file handling and dictionaries
- Goal: Understand how to read, write, and process CSV data
1. Introduction
"I could save data to a JSON file. But every spreadsheet I've ever seen exports to CSV. So I learned how to work with CSVs β and suddenly I could process real data."
2. What Is a CSV?
CSV stands for Comma-Separated Values. It's a plain text file where each line is a row, and each value is separated by a comma.
Example β a list of users:
name,age,city
Ali,25,Karachi
Sara,30,Lahore
Ahmed,28,Islamabad
That's it. No formatting, no colors, no formulas. Just text.
3. Why CSV Matters
- Every spreadsheet exports to CSV β Excel, Google Sheets, Numbers
- Every database can export to CSV β MySQL, PostgreSQL, SQLite
- Every data tool imports CSV β pandas, R, Tableau
If you can read and write CSV in Python, you can process real-world data.
4. Reading a CSV (The Manual Way)
You could read a CSV like a normal text file:
with open("users.csv", "r") as file:
for line in file:
print(line.strip().split(","))
Output:
['name', 'age', 'city']
['Ali', '25', 'Karachi']
['Sara', '30', 'Lahore']
It works β but notice that "25" is a string, not a number. And if any value contains a comma (like an address), this breaks.
That's why Python has a built-in csv module.
5. Reading a CSV (The Right Way)
import csv
with open("users.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
Output:
{'name': 'Ali', 'age': '25', 'city': 'Karachi'}
{'name': 'Sara', 'age': '30', 'city': 'Lahore'}
DictReader uses the first row as headers, and each row becomes a dictionary. Much cleaner.
6. Writing a CSV
import csv
users = [
{"name": "Ali", "age": 25, "city": "Karachi"},
{"name": "Sara", "age": 30, "city": "Lahore"}
]
with open("users.csv", "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["name", "age", "city"])
writer.writeheader()
writer.writerows(users)
Whatβs in the file:
name,age,city
Ali,25,Karachi
Sara,30,Lahore
Notice newline="". Without it, Python adds extra blank lines on Windows.
7. Real Example (Processing Data)
import csv
with open("users.csv", "r") as file:
reader = csv.DictReader(file)
adults = [row for row in reader if int(row["age"]) >= 30]
with open("adults.csv", "w", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["name", "age", "city"])
writer.writeheader()
writer.writerows(adults)
Thatβs a mini data pipeline: read. filter, write. Ten lines.
8. Common Mistakes Beginners Make
- Mistake 1: Forgetting newline=ββ when writing. You get blank lines between every row on windows.
- Mistake 2: Assuming values are numbers CSV values are always strings. Convert with int() or float() if needed.
- Mistake 3: Not handling missing files. Always check with os.path.exists() before reading.
- Mistake 4: Using wrong delimiter. Some CSVs use semicolons or tabs. Pass delimiter=β;β or delimiter=β\tβ if needed.
9. What I learned
- CSV is everywhere β it's the default export of every spreadsheet and database
- csv.DictReader gives you dictionaries instead of lists
- csv.DictWriter lets you write rows with named fields
- newline="" prevents blank lines on Windows
- All CSV values are strings β convert them yourself
10. Conclusion
"CSV files felt boring until I realized they're how the real world moves data around. Every spreadsheet, every database export, every report β it's all CSV underneath. Learning this opened up a new kind of project.β
Top comments (0)