csv

Reading and writing CSV files, that is tables saved as text in which values are separated by a comma or a semicolon.

Returns
reader and DictReader return an iterator of rows (lists or dictionaries), and writer and DictWriter an object with writing methods.
On this page

Example

#
Python
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))
Resultsaved result, you can check it
{'name': 'Emma', 'world': '7', 'points': '250'}
330

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

#
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 with open(..., 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. In DictWriter they are required and set the column order, in DictReader they are optional, taken from the first row by default.

More examples

#
Why split(",") is not enough
Python
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)
Resultsaved result, you can check it
['Emma', 'Python', '"Great', ' recommended"']
['name', 'course', 'review']
['Emma', 'Python', 'Great, recommended']
['Jack', 'HTML', 'Good']
Writing with a semicolon and quotes
Python
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())
Resultsaved result, you can check it
course;modules;description
Python;12;"Safari; Darwin"
HTML;11;"Markup ""from scratch"""

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.

A file for Excel with accented characters
Python
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=";")))
Resultsaved result, you can check it
[['Student', 'Grade'], ['Zoë', '5']]

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() or float(), and numbers with a decimal comma first with replace(",", ".").
  • For analyzing large tables, the pandas library is more convenient: pd.read_csv("file.csv", sep=";").

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.