473,322 Members | 1,510 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

line number var like perl's $.?

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.
Jul 18 '05 #1
5 6779
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.

Jul 18 '05 #2
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.
Alex

Jul 18 '05 #3
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2003-11-17T15:51:52Z, Matthew Wilson <mw*****@sarcastic-horse.com> writes:
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.


OTOH, I don't know that I've ever needed to track line numbers, other than
to do something like 'print "Lines:", linenum' after reading a bunch of
stuff from stdin.

I only mention this to illustrate that what's common to you is not
necessarily common to others. Your essential feature is another's cruft.
- --
Kirk Strauser
The Strauser Group
Open. Solutions. Simple.
http://www.strausergroup.com/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/uQqh5sRg+Y0CpvERAm6XAJwOsjML/se7yf6PGeNmHEqc8PvnmACcCllx
rkneNtVmVNKNiW3QPQ0i21Y=
=oaZV
-----END PGP SIGNATURE-----
Jul 18 '05 #4
Matthew Wilson <mw*****@sarcastic-horse.com> wrote in message news:<sl********************@overlook.homelinux.ne t>...
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";
} ....[snip]... 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.


In Python 2.3, you could use:

for linenum, line in enumerate(file('blah.txt')):
print linenum, '. ', line
Jul 18 '05 #5
Hello Matthew,
linenum = 0
for line in open('blah.txt'):
linenum += 1
print linenum, ". ", line

In 2.3 you can use "enumerate"
for lnum, line in enumerate(open("blah.txt")):
print lnum, ".", line

HTH.
Miki
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Ken Varn | last post by:
I want to be able to determine my current line, file, and function in my C# application. I know that C++ has the __LINE__, __FUNCTION__, and __FILE___ macros for getting this, but I cannot find a...
9
by: kangaroo | last post by:
Hi guys, when we run a stored proc and it results into an unhandled error, the error message returned by db2 udb does not contain a line number that caused an error. This makes it pretty...
2
by: johnivey | last post by:
I have a large query that I am trying to debug in query analyzer. However, the errors I get have no line number or reference to where they are failing. How can I find out what line in the query is...
7
by: Daniel | last post by:
hi guys i have never understood this so i am hoping someone can help. I have had errors in my app before where on closing it down i get a NullReferenceException error thrown BUT no line number...
3
by: Dan Holmes | last post by:
Server stack trace: at IVS.Framework.ControlNumberService.InstallComponent(Identity id, ControlNumberInfo ctrlNumber) in...
4
by: Jeff Jarrell | last post by:
I have a block of code that during development is prone to casting errors. It is mostly a DataReader type thing. It looks something like this. _prtPNID = myDLReader.GetString("prtPNID")...
6
by: Lastknight | last post by:
Hi all I have googled and get the follwing expression for deleting the particular line of a perl program... perl -p -i -e"s/.*\n//" filename I am not able to understand the...
11
by: Horacius ReX | last post by:
Hi, I have to search for a string on a big file. Once this string is found, I would need to get the number of the line in which the string is located on the file. Do you know how if this is...
4
by: mercuryshipzz | last post by:
Hi, My objective is to get the line number of the first occurance of the search pattern. my test.txt contains: ..... .................. total rows.... ................... ..
2
by: Greg M | last post by:
I'm not sure how to phrase the question so I'll just show what I'm trying to do. I have somewhere in a file: abcdefg1abcdefg abcdefg abcdefg abcdefg abcdefg I used regex to locate where...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.