What You Will Learn
Beginner
- How to read and write CSV files
- Using csv.reader and csv.DictReader
- Handling headers
Terminalpython
import csv
# Writing CSV
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "Grade"])
writer.writerow(["Anita", 28, "A"])
writer.writerow(["Ravi", 25, "B"])
# Reading CSV
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# ['Name', 'Age', 'Grade']
# ['Anita', '28', 'A']
# ['Ravi', '25', 'B']
# DictReader - access by column name
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["Name"], row["Grade"])
# Anita A
# Ravi BPractical Exercise
Write a CSV with 3 columns and 3 rows
Read it back with csv.reader
Read it with csv.DictReader - access by column name
Write a CSV from a list of dictionaries
Key Takeaways
- csv.writer: write rows with writerow().
- csv.reader: read rows as lists.
- csv.DictReader: read rows as dicts (access by column name).
- Always use newline='' when writing CSV on Windows.
- For large files, process line by line (do not read all at once).
Comments
Comments
Post a Comment