Python - Read the last line of file

By xngo on July 27, 2019

In Python, there are multiple ways to read the last line of a file. Some are simple, convenient or efficient and some are not.

Small file

For small file, you can load the whole file into memory and access the last line. Here is the example.

# Load the whole file into memory.
with open("myfile.txt", "r") as file:            
    lines=file.readlines()
print(lines[-1])

Big file

Obviously, for big file, you can't load the whole file into memory. Otherwise, you may run out of memory space. So, a better way would be to read through the file line by line and print the last line. Here is an example.

# Read line by line.
with open("myfile.txt", "r") as file:
    for line in file:
        pass
print(line)

Efficient way

Both solutions shown above are simple solutions but they are not the most efficient. They both have to waste time reading through the whole file. A more efficient way would be to jump to the end of the file and read it backward to find a newline. Here is an example.

import os
with open("myfile.txt", "rb") as file:
    file.seek(-2, os.SEEK_END)
    while file.read(1) != b'\n':
        file.seek(-2, os.SEEK_CUR) 
    print(file.readline().decode())

In order to seek the end of file, we have to open the file in binary mode. We seek to the last 2 characters since the file is likely to end with a newline. Then, keep reading a single byte until a newline character is found. And, finally, we use readline() to read the final line, and decode() to convert from bytes to string.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.