[Csv] PEP 305

Chris Munchenberg cjm at ava.com.au
Wed Oct 13 16:32:14 CEST 2004


I have been using the cvs module extensively, and find it very useful.

Ths only thing is that many of the csv files I use have headers - and 
the Dictionary Reader doesn't cope with them well. I've started using a 
slightly modified version. Feel free to do whatever - use it or delete 
it immediately from your inbox.

Chris Munchenberg.

from csv import reader

class MyDictReader:
    def __init__(self, f, fieldnames = None, restkey=None, restval=None,
                 dialect="excel", *args, **kwds):
        self.reader = reader(f, dialect, *args, **kwds)
        self.f = f
        if fieldnames:
            self.fieldnames = fieldnames    # list of keys for the dict
            self.fieldnames = self.reader.next() # use header row as 
keys for the dictionary
        self.restkey = restkey          # key to catch long rows
        self.restval = restval          # default value for short rows

    def __iter__(self):
        return self

    def next(self):
        row = self.reader.next()
        # unlike the basic reader, we prefer not to return blanks,
        # because we will typically wind up with a dict full of None
        # values
        while row == []:
            row = self.reader.next()
        d = dict(zip(self.fieldnames, row))
        lf = len(self.fieldnames)
        lr = len(row)
        if lf < lr:
            d[self.restkey] = row[lf:]
        elif lf > lr:
            for key in self.fieldnames[lr:]:
                d[key] = self.restval
        return d

    def reset(self):

More information about the Csv mailing list