Python: determine if the current line in the file is the last.

I read the file in Python one at a time, and I need to know which line is the last one when reading, something like this:

f = open("myfile.txt") for line in f: if line is lastline: #do smth 

From the examples, I found that it includes searching and fully reading files to count lines, etc. Can I only notice that the current line is the last? I tried to go and check for the existence of "\ n", but in many cases the last lines should not be followed by a backslash N.

Sorry if my question is superfluous as I did not find an answer to SO

+10
source share
6 answers
 secondLastLine = None lastLine = None with open("myfile.txt") as infile: secondLastLine, lastLine = infile.readline(), infile.readline() for line in infile: # do stuff secondLastLine = lastLine lastLine = line # do stuff with secondLastLine 
+3
source

Check if the is line is last line:

 with open("in.txt") as f: lines = f.readlines() last = lines[-1] for line in lines: if line is last: print id(line),id(last) # do work on lst line else: # work on other lines 

If you want the second last line to use last = lines[-2]

Or simply:

 with open("in.txt") as f: lines = f.readlines() last = lines[-1] for line in lines[:-1]: # work on all but last line # work on last 
+7
source
 import os path = 'myfile.txt' size = os.path.getsize(path) with open(path) as f: for line in f: size -= len(line) if not size: print('this is the last line') print(line) 
+7
source

One thing you could try is to try to get the next line and catch the exception if it occurs, because python AFAIK iterators do not have a hasNext built-in method.

+2
source

You can use itertools paired recipe ;

 with open('myfile.txt') as infile: a,b = itertools.tee(infile) next(b, None) pairs = zip(a,b) lastPair = None for lastPair in pairs: pass secondLastLine = lastPair[0] # do stuff with secondLastLine 
+2
source

This is an old question, but if you want to allow empty last lines, this is better:

 with open("myfile.txt") as f: while True: line = f.readline() # do smth if line[-1:] != '\n': # do smth with the last line break 

or more readable:

 with open("myfile.txt") as f: while True: line = f.readline() # do smth if not line.endswith('\n'): # do smth with the last line break 
0
source

Source: https://habr.com/ru/post/972922/


All Articles