Pythonic use of CSV module to skip headers?

Skip Montanaro skip at pobox.com
Sat Dec 4 15:59:34 CET 2004


    >> 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:

    Michael> I deal so much with tab-delimited CSV files that I found it
    Michael> useful to create a subclass of csv.DictReader to deal with
    Michael> this, so I can just write:

    Michael> for row in tabdelim.DictReader(file(filename)):
    Michael>      ...

    Michael> I think this is a lot easier than trying to remember this
    Michael> cumbersome idiom every single time.

I'm not sure what the use of TABs as delimiters has to do with the OP's
problem.  In my example I flubbed and failed to specify the delimiter to the
constructors (comma is the default delimiter).

You can create a subclass of DictReader that plucks the first line out as a
set of titles:

    class SmartDictReader(csv.DictReader):
        def __init__(self, f, *args, **kwds):
            rdr = csv.reader(*args, **kwds)
            titles = rdr.next()
            csv.DictReader.__init__(self, f, titles, *args, **kwds)

Is that what you were suggesting?  I don't find the couple extra lines of
code in my original example all that cumbersome to type though.

Skip



More information about the Python-list mailing list