readlines with line number support?

Nikhil mnikhil at gmail.com
Wed May 14 14:52:53 EDT 2008


Arnaud Delobelle wrote:
> Nikhil <mnikhil at gmail.com> writes:
> 
>> Hi,
>>
>> I am reading a file with readlines method of the filepointer object
>> returned by the open function. Along with reading the lines, I also
>> need to know which line number of the file is read in the loop
>> everytime.
>> I am sure, the line should have the property/attribute which will say
>> the line number of the file.
>>
>> If there is none, do I have to end up using the counter in the loop?
>>
>> fp = open("file", "r")
>> lineno = 0
>> for line in fp.readlines():
>> 	print "line number: " + lineno + ": " + line.rstrip()
>>         lineno = lineno + 1
> 
> The standard Python way is using enumerate()
> 
> for i, line in enumerate(fp):
>     print "line number: " + lineno + ": " + line.rstrip()
> 
Oh I did not know enumerate can be used. Thanks Paul and Arnaud.
I will try this.



More information about the Python-list mailing list