Python Notes and Examples

CSV Files

I keep a couple of utility functions under my pillow for reading and writing csv files:

import csv, os, io

# Read a csv file into a list of lists.
def read_csv(fnm):
    rows = []
    with io.open(fnm, newline='') as f:
        reader = csv.reader(f)
        for row in reader:
            rows.append(row)
    return rows

# Write a list of lists to a csv file.
lol = [
    ['size', 'color', 'angle'],
    [   '5', 'green',    '45'],
    [   '6', 'orange',   '50'],
]

# Writes a list of lists to a csv file. First list of the
# lol is the heading row.
def write_csv(fnm, lol):
    with io.open(fnm, 'w', newline='') as f:
        # You need this to get a regular non-DOS text file.
        writer = csv.writer(f, lineterminator=os.linesep)
        writer.writerows(lol)

If you leave out the lineterminator=os.linesep on GNU/Linux you’ll get funny “\r\n” line-endings.