[Tutor] line number when reading files using csv module

Duncan Gibson duncan at thermal.esa.int
Mon Oct 30 09:49:20 CET 2006


Duncan Gibson wrote:
> > 
> >     import csv
> > 
> >     class MyReader(object):
> >         
> >         def __init__(self, inputFile):
> >             self.reader = csv.reader(inputFile, delimiter=' ')
> >             self.lineNumber = 0
> > 
> >         def __iter__(self):
> >             self.lineNumber += 1
> >             return self.reader.__iter__()
> >
> > Is there some other __special__ method that I need to forward to the
> > csv.reader, or have I lost all control once __iter__ has done its job?

Kent Johnson wrote:
> __iter__() should return self, not self.reader.__iter__(), otherwise 
> Python is using the actual csv.reader not your wrapper. And don't 
> increment line number here.
> 
> You lost control because you gave it away.


Thanks Kent. The penny has dropped and it makes a lot more sense now.

I was looking for at __iter__ as a special function that *created* an
iterator, but all it really does is signal that the returned object
will implement the iterator interface, and the next() method in
particular. 

Cheers
Duncan


More information about the Tutor mailing list