Reputation: 11
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
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
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
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