Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Files Module 6 - File Handling & Errors Python Python Basics Python Programming: From Zero to Real-World Applications

Working with CSV Files in Python

Reviewed & accurate
AI Summary

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 B

Practical 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).
Previously: Lesson 37 covered file I/O.
Today: You learned: Process CSV files with the csv module.
Next: Lesson 39 covers exceptions.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments