Google Groups Home
Help | Sign in
Message from discussion readlines with line number support?
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
Arnaud Delobelle  
View profile
 More options May 14, 2:45 pm
Newsgroups: comp.lang.python
From: Arnaud Delobelle <arno...@googlemail.com>
Date: Wed, 14 May 2008 19:45:26 +0100
Local: Wed, May 14 2008 2:45 pm
Subject: Re: readlines with line number support?

Nikhil <mnik...@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()

--
Arnaud


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.

Create a group - Google Groups - Google Home - Terms of Service - Privacy Policy
©2008 Google