[Tutor] line number when reading files using csv module

Kent Johnson kent37 at tds.net
Fri Oct 27 12:11:16 CEST 2006


Duncan Gibson wrote:
> 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'

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.

Kent



More information about the Tutor mailing list