Python has built-in libraries to handle CSV files, making it easy to read from, write to, and process these file formats. Here are examples of how to work with both CSV files.
Python’s csv
module provides functionality to handle CSV (Comma-Separated Values) files.
Reading from a CSV File
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
csv.reader(file)
: Reads the CSV file line by line, where each row is a list.
Writing to a CSV File
import csv
data = [
["Name", "Age", "City"],
["John", 35, "London"],
["Tom", 30, "New York"],
]
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
csv.writer(file)
: Creates a writer object.
writer.writerows(data)
: Writes multiple rows to the file.
Using a Dictionary with CSV Files
The DictReader
and DictWriter
classes allow you to work with CSV data as dictionaries, which can be more intuitive.
Reading with DictReader
import csv
with open("data.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row) # Each row is a dictionary
Writing with DictWriter
import csv
data = [
{"Name": "John", "Age": 35, "City": "London"},
{"Name": "Tom", "Age": 30, "City": "New York"},
]
with open("data.csv", "w", newline="") as file:
fieldnames = ["Name", "Age", "City"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader() # Writes the field names as headers
writer.writerows(data)