close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to read the last line of a file in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

  1. How to read the last line of a file in Python?

    Why don't you just read all the lines and store the last line to the variable?
    with open('filename.txt', 'r') as f: last_line = f.readlines()[-1]

  2. read the last line of a file in Python

    Why don't you just read all the lines and store the last line to the variable?
    with open('filename.txt', 'r') as f: last_line = f.readlines()[-1]

Method 1

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()

Method 2

Why don’t you just read all the lines and store the last line to the variable?

with open('filename.txt', 'r') as f:
    last_line = f.readlines()[-1]

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read