12.20.5 Examples

The simplest example of reading a CSV file:

import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
    print row

Reading a file with an alternate format:

import csv
reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE)
for row in reader:
    print row

The corresponding simplest possible writing example is:

import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerows(someiterable)

Registering a new dialect:

import csv

csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)

reader = csv.reader(open("passwd", "rb"), 'unixpwd')

A slightly more advanced use of the reader - catching and reporting errors:

import csv, sys
filename = "some.csv"
reader = csv.reader(open(filename, "rb"))
try:
    for row in reader:
        print row
except csv.Error, e:
    sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))

And while the module doesn't directly support parsing strings, it can easily be done:

import csv
print csv.reader(['one,two,three'])[0]

The csv module doesn't directly support reading and writing Unicode, but it is 8-bit clean save for some problems with ASCII NUL characters, so you can write classes that handle the encoding and decoding for you as long as you avoid encodings like utf-16 that use NULs.

import csv

class UnicodeReader:
    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        self.reader = csv.reader(f, dialect=dialect, **kwds)
        self.encoding = encoding

    def next(self):
        row = self.reader.next()
        return [unicode(s, self.encoding) for s in row]

    def __iter__(self):
        return self

class UnicodeWriter:
    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        self.writer = csv.writer(f, dialect=dialect, **kwds)
        self.encoding = encoding

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

They should work just like the csv.reader and csv.writer classes but add an encoding parameter.

See About this document... for information on suggesting changes.