Python CSV Module
The csv module implements classes to read and write tabular data in CSV format.
Importing the Module
import csv
Reading CSV Files
csv.reader
To read a CSV file, you can use the csv.reader object.
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
csv.DictReader
The csv.DictReader class operates like a regular reader but maps the information in each row to a dictionary whose keys are given by the optional fieldnames parameter.
import csv
with open('data.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row['column_name'])
Writing CSV Files
csv.writer
To write to a CSV file, use the csv.writer object.
import csv
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["John", "30", "New York"])
csv.DictWriter
The csv.DictWriter class operates like a regular writer but maps dictionaries onto output rows.
import csv
with open('data.csv', 'w', newline='') as file:
fieldnames = ['name', 'age']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'name': 'John', 'age': 30})
writer.writerow({'name': 'Jane', 'age': 25})