[Tutor] line number when reading files using csv module
Duncan Gibson
duncan at thermal.esa.int
Fri Oct 27 14:25:28 CEST 2006
Kent Johnson wrote:
> The line_num attribute is new in Python 2.5. This is a doc bug,
> it should be noted in the description of line_num.
Is there some way to create a wrapper around a 2.4 csv.reader to
give me pseudo line number handling? I've been experimenting with:
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__()
def next(self):
self.lineNumber += 1 # do I need this one?
return self.reader.next()
if __name__ == '__main__':
inputFile = file('data.csv', 'rb')
reader = MyReader(inputFile)
for data in reader:
print reader.lineNumber, data
But that doesn't seem to do what I want. If I add some print statements
to the methods, I can see that it calls __iter__ only once:
__iter__
1 ['1', '2', '3']
1 ['2', '3', '4', '5']
1 ['3', '4', '5', '6', '7']
1 ['4', '5', '6', '7']
1 ['5', '6', '7', '8', '9']
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?
Cheers
Duncan
More information about the Tutor
mailing list