Python Notes and Examples
← prev | next →     Top-level ToC     /csv.html     (printable version)
import csv, os

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

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

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