[Csv] confused about wrapping readers and writers

Skip Montanaro skip at pobox.com
Sat Feb 8 21:13:01 CET 2003


I still want to be able to read from and write to dictionaries. ;-) I would
like to add a pair of classes to csv.py which implement this, but I don't
quite know what's required, never having written any iterators before.  If I
create a reader:

    >>> rdr = csv.reader(["a,b,c\r\n"])

and ask for its attributes, all I get back are the data attributes:

    >>> dir(rdr)
    ['delimiter', 'doublequote', 'escapechar', 'lineterminator',
    'quotechar', 'quoting', 'skipinitialspace', 'strict'] 

Does the underlying reader object need to expose its Reader_iternext
function as a next() method?  Based upon

    http://www.python.org/doc/current/lib/typeiter.html

I sort of suspect it does.  It looks like it also needs an __iter__() method
which just returns self.

I thought a DictReader would look something like

    class DictReader:
        def __init__(self, f, fieldnames, rest=None, dialect="excel", *args):
            self.fieldnames = fieldnames    # list of keys for the dict
            self.rest = rest                # key to catch long rows
            self.reader = reader(f, dialect, *args)

        def next(self):
            row = self.reader.next()
            d = dict(zip, self.fieldnames, row)
            if len(self.fieldnames) < len(row):
                d[self.rest] = row[len(self.fieldnames):]
            return d

Is all that's missing a next() method for reader objects?

Thx,

Skip



More information about the Csv mailing list