csv
Reading and writing CSV files, that is tables saved as text in which values are separated by a comma or a semicolon.
- Returns
readerandDictReaderreturn an iterator of rows (lists or dictionaries), andwriterandDictWriteran object with writing methods.
Example
#import csv
students = [
{"name": "Emma", "world": 7, "points": 250},
{"name": "Jack", "world": 2, "points": 80},
]
with open("results.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["name", "world", "points"])
writer.writeheader()
writer.writerows(students)
with open("results.csv", newline="", encoding="utf-8") as file:
rows = list(csv.DictReader(file))
print(rows[0])
print(sum(int(row["points"]) for row in rows))The results.csv file contains the header row name,world,points and two data rows. After reading, all the values are strings, so the points have to be converted with int().
Definition and usage
#The csv module reads and writes CSV files, that is tables as text: each row of the table is one line, and the values are separated by a separator, most often a comma. Excel, Google Sheets, and most databases export data in this format. The module correctly handles values that contain the separator or a quote, which are easy to break when splitting by hand with split(",").
csv.reader returns the successive rows as lists of strings, and csv.DictReader as dictionaries whose keys are the column names from the first row. For writing there are csv.writer with the writerow() and writerows() methods, and csv.DictWriter, which writes the header with the writeheader() method. All the values you read are strings, so you convert numbers yourself with int() or float().
Open the file with the newline="" argument and an explicit encoding, e.g. encoding="utf-8". Without newline="", empty lines appear between rows on Windows. Excel in some regional settings, for example the Polish one, uses a semicolon as the separator, which you set with the delimiter=";" parameter, and it displays accented characters correctly when you save the file in the "utf-8-sig" encoding.
Syntax
#import csv
csv.reader(f, delimiter=",")
csv.writer(f, delimiter=",")
csv.DictReader(f)
csv.DictWriter(f, fieldnames=[...])Parameters
#f
file object or list of strings
A file opened withopen(..., newline=""), or any collection of successive lines of text.delimiter
str, default ","
The value separator, e.g.";"for files from Excel in some regional settings.fieldnames
list of strings
The column names. InDictWriterthey are required and set the column order, inDictReaderthey are optional, taken from the first row by default.
More examples
#import csv
lines = [
"name,course,review",
'Emma,Python,"Great, recommended"',
"Jack,HTML,Good",
]
print(lines[1].split(","))
for row in csv.reader(lines):
print(row)import csv
import io
buffer = io.StringIO()
writer = csv.writer(buffer, delimiter=";", lineterminator="\n")
writer.writerow(["course", "modules", "description"])
writer.writerow(["Python", 12, "Safari; Darwin"])
writer.writerow(["HTML", 11, 'Markup "from scratch"'])
print(buffer.getvalue())A value containing the separator is put in quotes, and a quote inside a value is doubled. io.StringIO collects the text in memory here instead of in a file.
import csv
with open("grades.csv", "w", newline="", encoding="utf-8-sig") as file:
writer = csv.writer(file, delimiter=";")
writer.writerow(["Student", "Grade"])
writer.writerow(["Zoë", 5])
with open("grades.csv", newline="", encoding="utf-8-sig") as file:
print(list(csv.reader(file, delimiter=";")))The utf-8-sig encoding adds an invisible BOM marker at the start of the file, which Excel uses to recognize UTF-8 and display accented letters correctly.
Good practices
#- Open CSV files with
newline="". The module handles line endings itself, and without it empty rows will appear on Windows. - Values from the file are always strings. Convert numbers with
int()orfloat(), and numbers with a decimal comma first withreplace(",", "."). - For analyzing large tables, the pandas library is more convenient:
pd.read_csv("file.csv", sep=";").
Related entries
#- open()Opens a file for reading or writing and returns a file object.
- withA context manager: automatic setup and cleanup of resources.
- jsonConverts Python data to JSON text and back. The basis for saving data and communicating with APIs.
- str.split()Splits a string into a list of parts using a separator.
- next()Fetches the next item from an iterator. Once it is exhausted, returns a default value or raises StopIteration.
- dict()Creates a dictionary from key-value pairs or keyword arguments.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.