Re: Pythonic use of CSV module to skip headers?
From: Skip Montanaro (skip_at_pobox.com)
Date: 12/04/04
- Next message: Michael Hoffman: "Re: Pythonic use of CSV module to skip headers?"
- Previous message: Andrew James: "Import Semantics, or 'What's the scope of an import?', and class attribute instantiation"
- In reply to: Michael Hoffman: "Re: Pythonic use of CSV module to skip headers?"
- Next in thread: Michael Hoffman: "Re: Pythonic use of CSV module to skip headers?"
- Reply: Michael Hoffman: "Re: Pythonic use of CSV module to skip headers?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Michael Hoffman: "Re: Pythonic use of CSV module to skip headers?"
- Previous message: Andrew James: "Import Semantics, or 'What's the scope of an import?', and class attribute instantiation"
- In reply to: Michael Hoffman: "Re: Pythonic use of CSV module to skip headers?"
- Next in thread: Michael Hoffman: "Re: Pythonic use of CSV module to skip headers?"
- Reply: Michael Hoffman: "Re: Pythonic use of CSV module to skip headers?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|