an enumerate question

Steven Bethard steven.bethard at gmail.com
Mon Mar 19 23:00:23 EDT 2007


eight02645999 at 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/Cookbook/Python/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



More information about the Python-list mailing list