473,505 Members | 14,950 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

an enumerate question

hi
say i want to enumerate lines of a file
eg
for n,l in enumerate(open("file")):
# print next line ie

is there a way to print out the next line from current line using the
above?.
Or do i have to do a readlines() first to get it into a list eg
d = open("file").readlines()
for n, l in enumerate(d):
print d[n+1]

thanks

Mar 20 '07 #1
8 5018
ei***********@yahoo.com writes:
hi
say i want to enumerate lines of a file
eg
for n,l in enumerate(open("file")):
# print next line ie

is there a way to print out the next line from current line using the
above?.
I don't understand what you're trying to do. You mean you're
trying to print all lines except the first one?
Mar 20 '07 #2
On Mar 20, 9:48 am, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
eight02645...@yahoo.com writes:
hi
say i want to enumerate lines of a file
eg
for n,l in enumerate(open("file")):
# print next line ie
is there a way to print out the next line from current line using the
above?.

I don't understand what you're trying to do. You mean you're
trying to print all lines except the first one?
thanks for replying. sorry i make clear again.
say
for n,l in enumerate(open("file")):
print n,l # this prints current line
print next line in this current iteration of the loop.
hope you can understand now.
thanks.
Mar 20 '07 #3

eightthanks for replying. sorry i make clear again.
eightsay
eightfor n,l in enumerate(open("file")):
eight print n,l # this prints current line
eight print next line in this current iteration of the loop.

Off the top of my head, I'd try something like:

class TwoLiner:
def __init__(self, f):
self.f = f

def __iter__(self):
return self

def next(self):
line1 = self.f.next()
line2 = self.f.next()
return (line1, line2)

for n, (line1, line2) in enumerate(TwoLiner(open("file")):
print n, line1
print line2

Note that this has and end-of-file problem. When your file contains an odd
number of lines, at the end of the file TwoLiner.next will raise
StopIteration during the second self.f.next() call and you'll lose the last
line of the file. You can work around it with something like this:

def next(self):
line1 = self.f.next()
try:
line2 = self.f.next()
except StopIteration:
line2 = None
return (line1, line2)

then when using it you have to test line2 for None:

for n, (line1, line2) in enumerate(TwoLiner(open("file")):
print n, line1
if line2 is not None:
print line2

Skip
Mar 20 '07 #4
ei***********@yahoo.com writes:
for n,l in enumerate(open("file")):
print n,l # this prints current line
print next line in this current iteration of the loop.
hope you can understand now.
I see. It just seemed a little weird. If the file contains
first line
second line
third line

You want the output:

1 first line
second line
2 second line
third line
3 third line

Is that right?

Anyway all the ways I can think of to do it are at least somewhat
messy. Skip suggested one. It's easier if you're sure the file
is small enough to fit all its lines completely into memory.
Mar 20 '07 #5
ei***********@yahoo.com wrote:
for n,l in enumerate(open("file")):
print n,l # this prints current line
print next line in this current iteration of the loop.
Depends what you want to happen when you request "next". If you want to
renumber the lines, you can call .next() on the iterator::
>>open('temp.txt', 'w').write('1\n2\n3\n4\n5\n6\n7\n')
lines_iter = open('temp.txt')
for i, line in enumerate(lines_iter):
... print 'LINE %i, %r %r' % (i, line, lines_iter.next())
...
LINE 0, '1\n' '2\n'
LINE 1, '3\n' '4\n'
LINE 2, '5\n' '6\n'
Traceback (most recent call last):
File "<interactive input>", line 2, in <module>
StopIteration

If you want to peek ahead without removing the line from the iterator,
check out this recipe::

http://aspn.activestate.com/ASPN/Coo.../Recipe/304373

Which allows code like::
>>lines_iter = peekable(open('temp.txt'))
for i, line in enumerate(lines_iter):
... print 'LINE %i, %r %r' % (i, line, lines_iter.peek())
...
LINE 0, '1\n' '2\n'
LINE 1, '2\n' '3\n'
LINE 2, '3\n' '4\n'
LINE 3, '4\n' '5\n'
LINE 4, '5\n' '6\n'
LINE 5, '6\n' '7\n'
Traceback (most recent call last):
...
StopIteration

(Note that the recipe doesn't try to catch the StopIteration, but if you
want that suppressed, it should be a pretty simple change.)

STeVe
Mar 20 '07 #6
On Mar 20, 11:00 am, Steven Bethard <steven.beth...@gmail.comwrote:
eight02645...@yahoo.com wrote:
for n,l in enumerate(open("file")):
print n,l # this prints current line
print next line in this current iteration of the loop.

Depends what you want to happen when you request "next". If you want to
renumber the lines, you can call .next() on the iterator::
>>open('temp.txt', 'w').write('1\n2\n3\n4\n5\n6\n7\n')
>>lines_iter = open('temp.txt')
>>for i, line in enumerate(lines_iter):
... print 'LINE %i, %r %r' % (i, line, lines_iter.next())
...
LINE 0, '1\n' '2\n'
LINE 1, '3\n' '4\n'
LINE 2, '5\n' '6\n'
Traceback (most recent call last):
File "<interactive input>", line 2, in <module>
StopIteration

If you want to peek ahead without removing the line from the iterator,
check out this recipe::

http://aspn.activestate.com/ASPN/Coo.../Recipe/304373

Which allows code like::
>>lines_iter = peekable(open('temp.txt'))
>>for i, line in enumerate(lines_iter):
... print 'LINE %i, %r %r' % (i, line, lines_iter.peek())
...
LINE 0, '1\n' '2\n'
LINE 1, '2\n' '3\n'
LINE 2, '3\n' '4\n'
LINE 3, '4\n' '5\n'
LINE 4, '5\n' '6\n'
LINE 5, '6\n' '7\n'
Traceback (most recent call last):
...
StopIteration

(Note that the recipe doesn't try to catch the StopIteration, but if you
want that suppressed, it should be a pretty simple change.)

STeVe
thanks, lines_iter.next() is what i need at the moment.

Mar 20 '07 #7
ei***********@yahoo.com escreveu:
hi
say i want to enumerate lines of a file
eg
for n,l in enumerate(open("file")):
# print next line ie

is there a way to print out the next line from current line using the
above?.
Or do i have to do a readlines() first to get it into a list eg
d = open("file").readlines()
for n, l in enumerate(d):
print d[n+1]

thanks
for n,l in enumerate(file("file")):
print n,l[:-1] # the :-1 is to drop the \n - print n,l, also works (end
with ',').
HTH
Paulo

Mar 20 '07 #8
ei***********@yahoo.com wrote:
say i want to enumerate lines of a file
eg
for n,l in enumerate(open("file")):
# print next line ie
I think you'd find it much easier to move your frame of reference one
line forward and think in terms of remembering the previous line, e.g.:

for n,curr in enumerate(open("file")):
if n>1:
print n,curr
print m,prev
m,prev = n,curr

Of course, if the file isn't so big, then you could use readlines as you
mention.

Cheers,
Terry

--
Terry Hancock (ha*****@AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com

Mar 21 '07 #9

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

Similar topics

5
1657
by: Pekka Niiranen | last post by:
Hi, I have Perl code looping thru lines in the file: line: while (<INFILE>) { ... $_ = do something ... if (/#START/) { # Start inner loop
4
1336
by: Phillip N Rounds | last post by:
I need to eumerate all available drives in a C# Windows Form application ( and then of course the directory tree, but that's not the problem) My question is, how to I enumerate all the available...
5
3852
by: Gaetan | last post by:
I would like to guarantee that only one session at a time can request exclusive access to an object stored in Application. The ownership of the object must last throughout multiple HTTP requests. ...
1
1796
by: smichr | last post by:
I see that there is a thread of a similar topic that was posted recently ( enumerate with a start index ) but thought I would start a new thread since what I am suggesting is a little different. ...
6
2022
by: Gregory Petrosyan | last post by:
Hello! I have a question for the developer of enumerate(). Consider the following code: for x,y in coords(dots): print x, y When I want to iterate over enumerated sequence I expect this to...
2
2433
by: eight02645999 | last post by:
hi, i am using python 2.1. Can i use the code below to simulate the enumerate() function in 2.3? If not, how to simulate in 2.1? thanks from __future__ import generators def...
8
1404
by: Dustan | last post by:
Can I make enumerate(myObject) act differently? class A(object): def __getitem__(self, item): if item 0: return self.sequence elif item < 0: return self.sequence elif item == 0: raise...
21
2293
by: James Stroud | last post by:
I think that it would be handy for enumerate to behave as such: def enumerate(itrbl, start=0, step=1): i = start for it in itrbl: yield (i, it) i += step This allows much more flexibility...
12
2073
by: Danny Colligan | last post by:
In the following code snippet, I attempt to assign 10 to every index in the list a and fail because when I try to assign number to 10, number is a deep copy of the ith index (is this statement...
0
7216
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7098
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...
0
7303
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7367
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...
1
7018
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...
0
7471
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...
0
3187
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...
0
3176
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
407
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.