Python CSV Module: Reference and Examples

Last updated:
Table of Contents

Read a CSV file line by line

import csv

with open("path/to/file") as f:
    reader = csv.reader(f)

    for line in reader:
        # line is an array of strings

You can provide extra options, too. If you have a line like this:

"16","foo bar, baz","foo, bar \"...\" baz...",   "foo,bar, baz"

You need to instruct the reader to disconsider commas within double quotes and to use '\' to escape double quotes when inside a double-quoted block. You also need to tell it to disregard empty spaces before doublw quotes:

with open("path/to/file",'r') as f:
    reader = csv.reader(f,quotechar='"', delimiter=',', escapechar='\\', skipinitialspace=True)

    for line in reader:
        # line is an array of strings

Write CSV file using DictWriter

import csv

path_to_output_file = "my-file.csv"

with open(path_to_output_file, "w") as fout:

    # create a writer object and name the columns
    csv_writer = csv.DictWriter(fout, 
        escapechar='\\', # escape double quotes using a single backslash
        doublequote=False, # don't duplicate every double quote
        quoting=csv.QUOTE_ALL) # wrap every value in double quotes, for safety

    # optional: write a header

    # now write a line at a time
    csv_writer.writerow({'id':0, 'name': 'john'})
    csv_writer.writerow({'id':1, 'name': 'mary'})


Dialogue & Discussion