Re: Pythonic use of CSV module to skip headers?

From: Skip Montanaro (skip_at_pobox.com)
Date: 12/04/04


Date: Sat, 4 Dec 2004 08:59:34 -0600
To: Michael Hoffman <mh391@cam.ac.uk>


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



Relevant Pages

  • Re: simple ALTER TABLE question
    ... and the NOT NULL constraint added at column creation time makes sure ... "Michael C" wrote in message ... Finally, you should specify ...
    (microsoft.public.sqlserver.programming)
  • Re: passing a string with quotes as parameter
    ... it's SED (the stream editor - part of the cygwin utils ... Under GnuSED you specify an embedded double quote as \x22 ... >>> Michael ...
    (microsoft.public.win2000.cmdprompt.admin)
  • Re: N-Tier Dilemma and Transaction
    ... It's wrong to specify what's DB instance of DAL to create". ... "Michael Nemtsev" wrote: ... > B> - DataModel (referenced in BusinessLayer and DataLayer to communicate ... n assemblies specialized for the database. ...
    (microsoft.public.dotnet.distributed_apps)
  • Re: Drawing a line
    ... The place where you create new classes is where you specify the base class, ... How do I create a "subclass" of CStatic? ... if you want a "line" that is 256 pixels long where each pixel ...
    (microsoft.public.vc.mfc)
  • Re: Where is the entry point?
    ... subclass of RuntimeSessionManager (or ConsoleSessionManager) and you can ... specify this class as part of the deployment process. ...
    (comp.lang.smalltalk.dolphin)