How to read the last line of a file in Python?

How to read the last line of a file in Python?

A simple solution, which doesnt require storing the entire file in memory (e.g with file.readlines() or an equivalent construct):

with open(filename.txt) as f:
    for line in f:
        pass
    last_line = line

For large files it would be more efficient to seek to the end of the file, and move backwards to find a newline, e.g.:

import os

with open(filename.txt, rb) as f:
    try:  # catch OSError in case of a one line file 
        f.seek(-2, os.SEEK_END)
        while f.read(1) != bn:
            f.seek(-2, os.SEEK_CUR)
    except OSError:
        f.seek(0)
    last_line = f.readline().decode()

Note that the file has to be opened in binary mode, otherwise, it will be impossible to seek from the end.

Why dont you just read all the lines and store the last line to the variable?

with open(filename.txt, r) as f:
    last_line = f.readlines()[-1]

How to read the last line of a file in Python?

On systems that have a tail command, you could use tail, which for large files would relieve you of the necessity of reading the entire file.

from subprocess import Popen, PIPE
f = yourfilename.txt
# Get the last line from the file
p = Popen([tail,-1,f],shell=False, stderr=PIPE, stdout=PIPE)
res,err = p.communicate()
if err:
    print (err.decode())
else:
    # Use split to get the part of the line that you require
    res = res.decode().split(location=)[1].strip().split()[0]
    print (res)

Note: the decode() command is only required for python3

res = res.split(location=)[1].strip().split()[0]

would work for python2.x

Leave a Reply

Your email address will not be published.