How to Read Last Line of File Using Python

Muhammad Maisam Abbas Feb 02, 2024
  1. Read Last Line of File With the for Loop in Python
  2. Read Last Line of File With the readlines() Function in Python
How to Read Last Line of File Using Python

This tutorial will discuss the methods to read the last line from a file in Python.

Read Last Line of File With the for Loop in Python

The for loop is used to iterate through each element of an iterable in Python. We can use the for loop to iterate through each line inside a file sequentially and then read the last line of the file. The following code snippet shows us how to read the last line of a file with the for loop.

with open("file.txt", "r") as f:
    for line in f:
        pass
    last_line = line
print(last_line)

Output:

This is the last file

We opened the file.txt file in the read mode and used the for loop to iterate through each line in the file. We used the pass keyword to keep the loop empty. This pass keyword acts as a blank line in Python and is used when we don’t want to write any code inside a loop or a conditional statement. We store the last line inside the last_line variable when the loop ends and print its value.

Read Last Line of File With the readlines() Function in Python

The file.readlines() function reads all the lines of a file and returns them in the form of a list. We can then get the last line of the file by referencing the last index of the list using -1 as an index. The following code example shows us how to read the last line of a file with Python’s file.readlines() function.

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

Output:

This is the last file

We opened the file.txt file in the read mode and used the f.readlines()[-1] to read the last line of the file. We used [-1] because the readlines() function returns all the lines in the form of a list, and this [-1] index gives us the last element of that list.

In Python, no method can directly read the last line of a file. So, we have to read the whole file sequentially until we reach the last line. The first method reads the file line by line, while the second method reads all the lines simultaneously.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Python File