CSV and JSON files · 1 / 15 Theory

CSV files: reader and writer

CSV (*Comma-Separated Values*) is the simplest format to store tables of data: each line is a row and the values of each row are separated by commas. Spreadsheets (Excel, Google Sheets) and almost any program can read and write it.

name,age,city
Ana,30,Madrid
Luis,25,Lyon
Eva,41,Rome

The first line is usually the header, with the name of each column.

Why not use split(",")?

Because a value may contain a comma. In CSV, those values are written in quotes:

line = 'Ana,"Madrid, Spain",30'

print(line.split(","))
# ['Ana', '"Madrid', ' Spain"', '30']   (the field has been cut in two!)

The csv module knows how to interpret quotes correctly. With it you do not have to worry about those cases.

Reading with csv.reader

csv.reader takes any collection of lines (an open file or a list of texts) and returns each row as a list of texts:

import csv

lines = [
    "name,age,city",
    "Ana,30,Madrid",
    'Luis,25,"Lyon, France"',
]

for row in csv.reader(lines):
    print(row)
# ['name', 'age', 'city']
# ['Ana', '30', 'Madrid']
# ['Luis', '25', 'Lyon, France']

Notice that "Lyon, France" was read as a single value and without the quotes.

Reading a CSV file

To read a file, you open it with open giving newline="" and encoding="utf-8", and pass it to csv.reader:

import csv

with open("people.csv", "r", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    header = next(reader)         # first row: the column names
    for row in reader:
        print(row[0], row[1])     # name and age

next(reader) consumes the first row. That way the for loop starts right at the data.

Everything is text

CSV does not distinguish types: all values are read as str. If you want to operate with them, convert them:

row = ['Ana', '30', 'Madrid']

age = int(row[1])
print(age + 1)  # 31

price = float('1.20')
print(price * 3)  # 3.5999999999999996

Writing with csv.writer

csv.writer converts lists of values into CSV lines. It adds quotes only when they are needed:

import csv

with open("output.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "age"])         # one row
    writer.writerows([                        # several rows
        ["Ana", 30],
        ["Pérez, Luis", 25],
    ])

The content of the file will be:

name,age
Ana,30
"Pérez, Luis",25

Writing to a text in memory with StringIO

io.StringIO is a "fake file" that lives in memory. It is perfect for testing or for getting the CSV as text, without creating any file:

import csv
import io

output = io.StringIO()
writer = csv.writer(output, lineterminator="\n")
writer.writerow(["name", "age"])
writer.writerow(["Pérez, Luis", 25])

print(output.getvalue())
# name,age
# "Pérez, Luis",25

By default csv.writer ends each line with \r\n. With lineterminator="\n" it uses a normal line break.

Other separators

In some countries Excel uses the semicolon as a separator. It is given with delimiter:

lines = ["Ana;30;Madrid", "Luis;25;Lyon"]

for row in csv.reader(lines, delimiter=";"):
    print(row)
# ['Ana', '30', 'Madrid']
# ['Luis', '25', 'Lyon']

Practice in Column total, Quoted fields and Writing a CSV.