Krishna
Krishna

Reputation: 11

How to loop through all lines in a file except last in python?

I want to loop through all lines except last and print them. I was able to find some shell commands that print all lines except last, but i would like to use python to go over all lines except last. Pleas help.

Upvotes: 0

Views: 6442

Answers (3)

SWdream
SWdream

Reputation: 215

Please try this code:

In [1]: with open(filename) as f:
   ...:     data = f.read().split('\n')
   ...:     

In [2]: for id in range(len(data) -1):
   ...:     print data[id]
   ...: 

Upvotes: 0

chepner
chepner

Reputation: 531235

You'll have to read each line, save it, then work with them on the next iteration. That way, you never process the last line.

prev_line = None
for line in filehandler:
    if prev_line is not None:
        print prev_line
    prev_line = line

Upvotes: 2

Josh Weinstein
Josh Weinstein

Reputation: 2968

Best way to do this is to use a list slice that excludes the very last element of the list.

def print_lines(lst):
   for line in lst[0:len(lst)-1]:
      print(line)

This approach doesn't depend on whether or not a newline character is present at the end of the last line or not.

Upvotes: 0

Related Questions