skip last line in loops

Fredrik Lundh fredrik at pythonware.com
Fri Dec 15 02:36:17 EST 2006


eight02645999 at yahoo.com wrote:

> how can i skip printing the last line using loops (for /while)
> 
> eg
> 
> for line in open("file):
>      print line.
> 
> I want to skip printing last line of the file.

do it lazily:

     last_line = None
     for line in open("file):
         if last_line:
             print last_line
         last_line = line

or just gobble up the entire file, and slice off the last item:

     for line in list(open("file"))[:-1]:
         print line

</F>




More information about the Python-list mailing list