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

A simple solution, which doesn’t 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) != b'\n':
            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.

Leave a Comment