How to Read the Last Line of a File in Python?

I faced this issue while working on a project that involved monitoring real-time data logs for a tech company based in Silicon Valley. Let us get into the solutions with some important methods. In this tutorial, I will explain how to read the last line of a file in Python with suitable examples.

Read the Last Line of a File in Python

When dealing with log files or continuous data streams, the most recent information is often the most relevant. For instance, if you’re monitoring server logs for errors, the last line might contain the latest error message. Similarly, in financial applications, the last line of a stock price file might have the most recent price update.

[2024-02-06 10:16:45] WARNING  High memory usage detected (85%)
[2024-02-06 10:18:10] ERROR  Database connection failed: Timeout error
[2024-02-06 10:15:32] INFO  Server started successfully on port 8080

Assume you have this data inside the server_logs.txt file.

Read How to List Files in a Directory with Python?

Method 1: Use readlines() Method

The readlines() method in Python reads all lines in a file and returns them as a list. You can then access the last element of this list to get the last line.

def read_last_line(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        return lines[-1] if lines else None

# Example usage
file_path = 'C:/data/server_logs.txt'
print(read_last_line(file_path))

Output:

[2024-02-06 10:15:32] INFO  Server started successfully on port 8080

You can see the output in the below screenshot.

Read the Last Line of a File in Python

This method is simple but not efficient for large files since it reads the entire file into memory.

Check out How to Read the First Line of a File in Python?

Method 2: Use seek() and tell() Methods

For large files, a more efficient approach is to use the seek() and tell() methods in Python to navigate the file from the end.

Date,Revenue,Expenses,Profit
2024-01-01,5000,3000,2000
2024-01-02,7000,4000,3000

Assume you have this data inside the financial_data.txt file.

def read_last_line(file_path):
    with open(file_path, 'rb') as file:
        file.seek(-2, 2)  # Move the cursor to the second last byte
        while file.read(1) != b'\n':  # Move backward until finding a newline
            file.seek(-2, 1)
        return file.readline().decode()

# Example usage
file_path = 'C:/data/financial_data.txt'
print(read_last_line(file_path))

Output:

2024-01-02,7000,4000,3000

You can see the output in the below screenshot.

How to Read the Last Line of a File in Python

This method is more memory-efficient as it only reads the necessary part of the file.

Read How to Split a File into Multiple Files in Python?

Method 3: Use deque from collections

The deque class from the Python collections module can be used to read the last few lines of a file efficiently.

2024-02-06 10:17:45 | User: JaneSmith | Action: Refund | Amount: $30.00 | Status: Success  
2024-02-06 10:20:10 | User: AlexBrown | Action: Purchase | Amount: $75.50 | Status: Failed  
2024-02-06 10:25:32 | User: EmilyWhite | Action: Withdrawal | Amount: $200.00 | Status: Success

Assume you have this data inside the transaction_logs.txt file.

from collections import deque

def read_last_line(file_path):
    with open(file_path, 'r') as file:
        last_line = deque(file, maxlen=1).pop()
        return last_line

# Example usage
file_path = 'C:/data/transaction_logs.txt'
print(read_last_line(file_path))

Output:

2024-02-06 10:25:32 | User: EmilyWhite | Action: Withdrawal | Amount: $200.00 | Status: Success

You can see the output in the below screenshot.

Read the Last Line of a File in Python deque from collections

This approach is also efficient for reading the last few lines without loading the entire file into memory.

Check out How to Read Tab-Delimited Files in Python?

Examples

Let us learn more about reading the last line of a file by considering real-time examples.

Example 1: Read the Last Line of a Server Log File

Imagine you are monitoring server logs for a tech company in San Francisco. The log file is located at C:/data/server_logs.txt. You need to get the most recent log entry to check for errors.

file_path = 'C:/data/server_logs.txt'
last_log_entry = read_last_line(file_path)
print(f"Most recent log entry: {last_log_entry}")

Read How to Get the File Size in MB using Python?

Example 2: Read the Latest Financial Data

Suppose you are working with financial data for a New York-based investment firm. The data file is C:/data/financial_data.txt, and you need the latest stock price update.

file_path = 'C:/data/financial_data.txt'
latest_stock_price = read_last_line(file_path)
print(f"Latest stock price: {latest_stock_price}")

Check out How to Check If a File Exists and Create It If Not in Python?

Conclusion

In this tutorial, I helped you to learn how to read the last line of a file in Python. I discussed mainly three methods to achieve this task such as using the readlines() method, using seek() and tell() methods, and using deque from collections. I also covered some real-time examples.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.