To read the last N Lines of a file in Python, the easiest way is to use the Python file readlines() function and then access the last N elements of the returned list.

n = 5

with open("example.txt") as f:
    last_n_lines = f.readlines()[-n:]

When working with files, the ability to easily read from or write to a file is valuable.

One such case is if you want to read the last N lines of a file.

The easiest way to read the last N lines of a file in Python is with the Python file readlines() function.

readlines() reads all of the lines and returns a list.

After using readlines(), you can get the last N elements of the list, which will be the last N lines of the file.

Below is a simple example which shows you how to get the last N lines of a file with readlines() in Python.

n = 5

with open("example.txt") as f:
    last_n_lines = f.readlines()[-n:]

How to Read Last Line of File in Python

If you just want to read the last line of a file, you can use a simple method as above.

The easiest way, in our opinion, is with the file readlines() function. readlines() reads all of the lines and returns a list.

After using readlines(), you can get the last element of the list, which will be the last line of the file.

Below is an example showing how you can get the last line of a file using readlines() in Python.

with open("example.txt") as f:
    last_line = f.readlines()[-1]

Hopefully this article has been useful for you to learn how to read the last N lines of a file in Python.

Categorized in:

Python,

Last Update: February 26, 2024