line number var like perl's $.?
anton muhin
antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Mon Nov 17 11:08:57 EST 2003
Matthew Wilson wrote:
> One thing I miss about perl was the builtin $. variable that gets
> increased after each call to perl's file iterator object. For example:
>
> while ( my $line = <IN>) {
> print "$. $line";
> }
>
> or, more perlish:
>
> while (<IN>) {
> print "$. $_";
> }
>
> Tracking line numbers is such a common thing to do when parsing files
> that it makes sense for there to be a builtin for it.
>
> Is there an equivalent construct in python? Or are people doing
> something like this:
>
> linenum = 0
> for line in open('blah.txt'):
> linenum += 1
> print linenum, ". ", line
>
> Better ideas are welcomed.
If you upgrade to 2.3, you can use enumerate built-in:
for no, line in enumerate(file('blah.txt')):
print no, line
should work (I didn't test it however)
Otherwise you can create enumerate yourself:
from __future__ import generators
def enumerate(it):
n = 0
for e in it:
yield n, e
n += 1
Or to use xrange trick:
import sys
for no, line in zip(xrange(0, sys.maxint), file('blah.txt')):
print no, line
(not tested either).
regards,
anton.
More information about the Python-list
mailing list