Pythonic use of CSV module to skip headers?

Skip Montanaro skip at
Sat Dec 4 03:15:04 CET 2004

    Ramon> I'm using the csv module to parse a tab-delimited file and
    Ramon> wondered whether there was a more elegant way to skip an possible
    Ramon> header line.

Assuming the header line has descriptive titles, I prefer the DictReader
class.  Unfortunately, it requires you to specify the titles in its
constructor.  My usual idiom is the following:

    f = open(filename, "rb")        # don't forget the 'b'!
    reader = csv.reader(f)
    titles =
    reader = csv.DictReader(f, titles)
    for row in reader:

The advantage of the DictReader class is that you get dictionaries keyed by
the titles instead of tuples.  The code to manipulate them is more readable
and insensitive to changes in the order of the columns.  On the down side,
if the titles aren't always named the same you lose.


More information about the Python-list mailing list