Python and CSV

· by

Contents

Python has a very nice module called csv which makes working with CSV very easy. This mini article is only a reminder for me so that I can easily find how to use it when I forget once again how it is used exactly.

Reading CSV files

try:
    from future.builtins import open
except:
    pass

import csv

with open("eggs.csv", "rt", newline="") as csvfile:
    csvreader = csv.reader(csvfile, delimiter=";", quotechar='"')
    next(csvreader, None)  # skip the headers
    for row in csvreader:
        print(", ".join(row))

Writing CSV files

try:
    from future.builtins import open
except:
    pass

import csv

with open("eggs.csv", "w", newline="") as csvfile:
    csvwriter = csv.writer(
        csvfile, delimiter=";", quotechar='"', quoting=csv.QUOTE_MINIMAL
    )
    csvwriter.writerow(["Spam"] * 5 + ["Baked Beans"])  # Write header
    for row in container:
        csvwriter.writerow(row)  # Write data

See also