473,604 Members | 2,618 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

readlines with line number support?

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

--

Thanks,
Nikhil
Jun 27 '08 #1
7 5851
Nikhil wrote:
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
Untested:

for lineno, line in enumerate(open( "file")):
print "line number: %s : %s" % (idx, line.rstrip())

Note the other stylistic changes, too.
HTH.
Paul
Jun 27 '08 #2
Nikhil <mn*****@gmail. comwrites:
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

Jun 27 '08 #3
Arnaud Delobelle wrote:
Nikhil <mn*****@gmail. comwrites:
>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.
Jun 27 '08 #4
Arnaud Delobelle wrote:
Nikhil <mn*****@gmail. comwrites:
>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.
Jun 27 '08 #5
Arnaud Delobelle wrote:
The standard Python way is using enumerate()

for i, line in enumerate(fp):
print "line number: " + lineno + ": " + line.rstrip()
I guess you meant to say :

for lineno, line in enumerate(fp):
print "line number: " + lineno + ": " + line.rstrip()

Thanks.
Jun 27 '08 #6
Nikhil <mn*****@gmail. comwrites:
Arnaud Delobelle wrote:
>The standard Python way is using enumerate()

for i, line in enumerate(fp):
print "line number: " + lineno + ": " + line.rstrip()

I guess you meant to say :

for lineno, line in enumerate(fp):
print "line number: " + lineno + ": " + line.rstrip()
Yes!

--
Arnaud
Jun 27 '08 #7
Arnaud,
>Is there any way to have enumerate() start at 1 vs. 0?

The problem with starting at 0 is that many things in the real world
begin at 1 - like line numbers or labels in a list.
I suppose you could redefine enumerate to support an optional argument:

from itertools import izip, count

def enumerate(itera ble, start=0):
return izip(count(star t), iterable)
>>list(enumerat e('spam', 1))
[(1, 's'), (2, 'p'), (3, 'a'), (4, 'm')]
Brilliant!!

Thank you,
Malcolm
Jun 27 '08 #8

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

Similar topics

3
11521
by: Leeds, Mark | last post by:
I did more investigation into my previous problem and what happens is that my text file has \r for representing a new line instead of a \n. is there a way to tell the readlines function that the symbol for a newline is \r rather than \n ? right now the readlines function reads the\r as another item in the list and just puts everything into one big list because it doesn't find any new line characters. thanks. i'm really stuck because
5
3878
by: Richard | last post by:
Hi, Can anyone tell me what the difference is between for line in file.readlines( ): and for line in file:
2
6199
by: Yong Wang | last post by:
Hi, I use readlines() to read one data file. Python automatically parses the read contents into a list of lines. When I used list to print out the 1st line, it is ok. When I use the list index 2 to print out the 2nd line , there is an error mesage. I only need one line of input data file in the middle of the file. For example, I have data file like: --------------------------------------------------------------------------- Timestamp: Sat...
9
29217
by: wordsender | last post by:
Hey guys, I can't figure this one out, why is this simple script giving me problems? logfile=file(r'test.txt','w') logfile.write('datetime') test=logfile.readlines() When I run it I get the error message:
2
4145
by: vch | last post by:
Does a call to file.readlines() reads all lines at once in the memory? Are the any reasons, from the performance point of view, to prefer *while* loop with readline() to *for* loop with readlines()?
34
2791
by: Ross Reyes | last post by:
HI - Sorry for maybe a too simple a question but I googled and also checked my reference O'Reilly Learning Python book and I did not find a satisfactory answer. When I use readlines, what happens if the number of lines is huge? I have a very big file (4GB) I want to read in, but I'm sure there must be some limitation to readlines and I'd like to know how it is handled by python. I am using it like this:
4
1459
by: wscrsurfdude | last post by:
Ik have an uml file I want to read with readlines. I have the following code: infile = open("out2.txt","r") for line in infile.readlines(): print line The print statement just gives the data, not the uml headings. Is there a solution which also gives the uml headings.
0
943
by: tim | last post by:
I have a module based app that can load many modules at startup. The modules are text based with a '\t' separating the keyword from the definition. The app reads each module to extract the keywords, but because readlines() must read to the end of the current line to get to the next, the module loading is slow. Is there a way to have readlines() go to the next line when it finds a tab '\t' instead of a newline '\n'? Is there a better way to...
7
4093
by: Wojciech Gryc | last post by:
Hi, I'm currently using Python to deal with a fairly large text file (800 MB), which I know has about 85,000 lines of text. I can confirm this because (1) I built the file myself, and (2) running a basic Java program to count lines yields a number in that range. However, when I use Python's various methods -- readline(), readlines(), or xreadlines() and loop through the lines of the file, the line program exits at 16,000 lines. No...
0
7929
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8406
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8065
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8274
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
3906
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3954
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2433
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1522
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.