line number var like perl's $.?

Alex Martelli aleax at
Mon Nov 17 17:18:54 CET 2003

Matthew Wilson wrote:
> 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.

Python disagrees with you, and prefers to keep things in modules, in
most cases, rather than shoveling them wholesale into the builtins.

The module that's roughly equivalent to perl's "while(<something>)" is
named fileinput.  The task you sketch above, in Python, would normally
be coded more or less as follows:

import fileinput

for line in fileinput.input("readme.html"):
     print fileinput.lineno(), line,

There are several other possible approaches, but I find that fileinput
generally affords the smoothest translation of perl input idioms.


More information about the Python-list mailing list