The CSV Library in Python
Python’s csv library provides tools for working with CSV (Comma Separated Values) files, making it simple and effective to read, write and manipulate tabular data.
The library is included in Python’s standard library: nothing needs to be installed.
import csv
The examples in this guide use a file students.csv with columns: id, surname, name, subject, grade.
Reading with csv.reader
csv.reader returns an iterator that yields a list for each row of the file.
import csv
with open('students.csv', mode='r', newline='') as file:
reader = csv.reader(file)
header = next(reader) # skip the header row
for row in reader:
print(row)
# row is a list: ['12345', 'Rossi', 'Mario', 'Maths', '28']
next(reader)reads and discards the first row (header)- Each subsequent row is returned as a list of strings
Writing with csv.writer
csv.writer lets you write rows to a CSV file.
import csv
student_data = [
['12345', 'Rossi', 'Mario', 'Maths', '28'],
['67890', 'Bianchi', 'Luca', 'Physics', '30'],
['54321', 'Verdi', 'Anna', 'Chemistry','27'],
]
with open('students_out.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['id', 'surname', 'name', 'subject', 'grade'])
writer.writerows(student_data)
| Method | Description |
|---|---|
writerow(list) | Writes a single row |
writerows(list_of_lists) | Writes multiple rows in a single call |
Reading as a dictionary with DictReader
DictReader reads each row as a dictionary, using the first row of the file as keys.
import csv
with open('students.csv', mode='r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
print(row['id'], row['surname'], row['name'],
row['subject'], row['grade'])
Each row is a dictionary such as:
{'id': '12345', 'surname': 'Rossi', 'name': 'Mario', 'subject': 'Maths', 'grade': '28'}
Reading a CSV without a header
If the file has no header, specify the column names manually with fieldnames:
import csv
fields = ['id', 'surname', 'name', 'subject', 'grade']
with open('students_no_header.csv', mode='r', newline='') as file:
reader = csv.DictReader(file, fieldnames=fields)
for row in reader:
print(row['id'], row['surname'], row['name'])
Writing from dictionaries with DictWriter
DictWriter writes rows from dictionaries.
import csv
student_data = [
{'id': '12345', 'surname': 'Rossi', 'name': 'Mario', 'subject': 'Maths', 'grade': '28'},
{'id': '67890', 'surname': 'Bianchi', 'name': 'Luca', 'subject': 'Physics', 'grade': '30'},
{'id': '54321', 'surname': 'Verdi', 'name': 'Anna', 'subject': 'Chemistry','grade': '27'},
]
fields = ['id', 'surname', 'name', 'subject', 'grade']
with open('students_dict_out.csv', mode='w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader() # writes the header row
writer.writerows(student_data)
Class and method reference
| Class / Function | Use | Data type |
|---|---|---|
csv.reader(file) | Row-by-row reading | List per row |
csv.writer(file) | Row-by-row writing | List per row |
csv.DictReader(file) | Reading with column keys | Dict per row |
csv.DictWriter(file, fieldnames) | Writing from dicts | Dict per row |
Writer methods
| Method | Description |
|---|---|
writerow(row) | Writes one row (list or dictionary) |
writerows(rows) | Writes multiple rows |
writeheader() | Writes the header row (DictWriter) |
Practical notes
- Always use
newline=''when opening files to avoid blank lines on Windows. - The
'w'mode overwrites the file; use'a'to append. - Values are always strings: convert explicitly with
int()orfloat()as needed.
for row in reader:
grade = int(row['grade'])
print(f"{row['name']} {row['surname']}: {grade}/30")
EC