Python:Detect if the current line in file read is the last one

Check if line is the 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 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

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)

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

Tags:

Python