[Tutor] line number when reading files using csv module

Duncan Gibson duncan at thermal.esa.int
Fri Oct 27 11:35:40 CEST 2006

If I have the following data file, data.csv:
    1 2 3
    2 3 4 5

then I can read it in Python 2.4 on linux using:

    import csv
    f = file('data.csv', 'rb')
    reader = csv.reader(f)
    for data in reader:
        print data

OK, that's all well and good, but I would like to record
the line number in the file. According to the documentation,
each reader object has a public 'line_num' attribute
http://docs.python.org/lib/node265.html and
http://docs.python.org/lib/csv-examples.html supports this.

If I now change the loop to read:

    for data in reader:
        print reader.line_num, data

I'm presented with the error:
AttributeError: '_csv.reader' object has no attribute 'line_num'

This has floored me. I've even looked at the source code and I can
see the line_num variable in the underlying _csv.c file. I can even
see the test_csv.py code that checks it!

    def test_read_linenum(self):
        r = csv.reader(['line,1', 'line,2', 'line,3'])
        self.assertEqual(r.line_num, 0)

I suspect this is something so obvious that I just can't see the
wood for the trees and I will kick myself.

Any ideas?


More information about the Tutor mailing list