CSV File Parsing
CSV (Comma-Separated Values) files are widely used for storing tabular data, such as spreadsheets or simple databases.
Python’s built-in csv module provides convenient tools for reading and writing CSV files.
Note: The Python practice environment doesn’t support importing files from your local machine. The examples below are for demonstration purposes only.
1. Reading a CSV File
Use csv.reader() to read rows from a CSV file one at a time.
Reading a CSV File
import csv
with open("people.csv", newline="") as file:
reader = csv.reader(file)
for row in reader:
print(row)
- 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 to a CSV file.
Writing to 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])
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, making it easier to work with named columns.
Reading as Dictionaries
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.")
- 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 |
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.