CSV File Parsing
CSV (Comma-Separated Values) files are commonly used for storing tabular data — like spreadsheets.
Python’s built-in csv
module makes it easy to read from and write to CSV files.
1. Reading a CSV File
Use csv.reader()
to access rows from a CSV file.
import csv with open("people.csv", newline="") as file: reader = csv.reader(file) for row in reader: print(row)
Explanation:
- Each row is a list of values (split by commas).
newline=""
avoids issues with extra blank lines on Windows.
2. Writing to a CSV File
Use csv.writer()
to create and write rows into a CSV file.
import csv with open("new_people.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerow(["Name", "Age"]) writer.writerow(["Alice", 28]) writer.writerow(["Bob", 34])
Explanation:
writerow()
writes a list as one row in the file.- First row usually contains headers.
3. Reading as Dictionaries
csv.DictReader()
reads each row as a dictionary — good for working with named columns.
import csv with open("people.csv", newline="") as file: reader = csv.DictReader(file) for row in reader: print(row["Name"], "is", row["Age"], "years old.")
Explanation:
- You can access columns by their header names like
"Name"
and"Age"
.
Summary
Function | Description |
---|---|
csv.reader() | Reads CSV rows as lists |
csv.writer() | Writes rows to a CSV file |
csv.DictReader() | Reads rows as dictionaries |
What’s Next?
Next, you’ll explore how to use Python's built-in modules like math
, random
, and datetime
to enhance your programs.
Quiz
0 / 1
What function should you use to read rows from a CSV file as dictionaries in Python?
csv.reader()
csv.writer()
csv.DictReader()
csv.DictWriter()
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result