The Wayback Machine - https://web.archive.org/web/20240620212712/https://www.geeksforgeeks.org/python-reading-last-n-lines-of-a-file/
Open In App

Python – Reading last N lines of a file

Last Updated : 20 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Read a file line-by-line in Python
Given a text file fname, a number N, the task is to read the last N lines of the file.
As we know, Python provides multiple in-built features and modules for handling files. Let’s discuss different ways to read last N lines of a file using Python. 
File: 
 

Image of content of a file

Method 1: Naive approach 
In this approach, the idea is to use a negative iterator with the readlines() function to read all the lines requested by the user from the end of file.
 

Python3




# Python implementation to
# read last N lines of a file
 
# Function to read
# last N lines of the file
def LastNlines(fname, N):
    # opening file using with() method
    # so that file get closed
    # after completing work
    with open(fname) as file:
         
        # loop to read iterate
        # last n lines and print it
        for line in (file.readlines() [-N:]):
            print(line, end ='')
 
 
# Driver Code:
if __name__ == '__main__':
    fname = 'File1.txt'
    N = 3
    try:
        LastNlines(fname, N)
    except:
        print('File not found'


Output: 
 

Eighth line
Ninth line
Tenth line

 
Method 2: Using OS module and buffering policy 
In this approach, the idea is to work on the buffering policy in the python. A buffer stores a part of data received from a file stream of the operating system for a time period it is used and then more data comes in. 
The buffer size determines the size of the data that can be stored at a time until it is used. We have the option to pass an integer to buffering in order to set buffering policy and if we do not specify any policy then the size of the buffer depends upon the device’s block size. Usually, the buffer is 4096 or 8192 bytes long. In this approach size of the buffer is 8192 bytes.
Moreover, the st_size attribute of os.stat() method in the OS module is used to represent the size of the file in bytes.
Below is the implementation of the above approach.
 

Python3




# Python implementation to
# read last N lines of a file
# Using OS module and buffering policy
         
# importing os module
import os
 
# Function to read
# last N lines of the file
def LastNlines(fname, N):
    # taking buffer size of 8192 bytes
    bufsize = 8192
     
    # calculating size of
    # file in bytes
    fsize = os.stat(fname).st_size
     
    iter = 0
     
    # opening file using with() method
    # so that file get closed
    # after completing work
    with open(fname) as f:
        if bufsize > fsize:
                 
            # adjusting buffer size
            # according to size
            # of file
            bufsize = fsize-1
             
            # list to store
            # last N lines
            fetched_lines = []
             
            # while loop to
            # fetch last N lines
            while True:
                iter += 1
                 
                # moving cursor to
                # the last Nth line
                # of file
                f.seek(fsize-bufsize * iter)
                 
                # storing each line
                # in list upto
                # end of file
                fetched_lines.extend(f.readlines())
                 
                # halting the program
                # when size of list
                # is equal or greater to
                # the number of lines requested or
                # when we reach end of file
                if len(fetched_lines) >= N or f.tell() == 0:
                        print(''.join(fetched_lines[-N:]))
                        break
                         
# Driver Code:
if __name__ == '__main__':
     
    fname = 'File1.txt'
    N = 3
     
    try:
        LastNlines(fname, N)
    except:
        print('File not found')


Output: 
 

Eighth line
Ninth line
Tenth line

  
Method 3: Through Exponential search
In this method, the idea is to use Exponential Search algorithm which is generally used for searching sorted, unbounded or infinite lists. To get information about exponential search click here.
This approach uses assert statement which acts as a debugging tool to checks a condition. The program will continue to execute if the given statement is true otherwise, it generates an AssertionError exception. To get more details of assert statements click here.
Click here to get familiar with different kinds of use of seek() method.
Below is the implementation of the above approach.
 

Python3




# Python implementation to
# read last N lines of a file
# through Exponential search
         
# Function to read
# last N lines of the file
def LastNlines(fname, N):
     
    # assert statement check
    # a condition
    assert N >= 0
     
    # declaring variable
    # to implement
    # exponential search
    pos = N + 1
     
    # list to store
    # last N lines
    lines = []
     
    # opening file using with() method
    # so that file get closed
    # after completing work
    with open(fname) as f:
         
        # loop which runs
        # until size of list
        # becomes equal to N
        while len(lines) <= N:
             
            # try block
            try:
                # moving cursor from
                # left side to
                # pos line from end
                f.seek(-pos, 2)
         
            # exception block
            # to handle any run
            # time error
            except IOError:
                f.seek(0)
                break
             
            # finally block
            # to add lines
            # to list after
            # each iteration
            finally:
                lines = list(f)
             
            # increasing value
            # of variable
            # exponentially
            pos *= 2
             
    # returning the
    # whole list
    # which stores last
    # N lines
    return lines[-N:]
 
# Driver Code:
if __name__ == '__main__':
    fname = 'File1.txt'
    N = 3
    try:
        lines = LastNlines(fname, N)
        for line in lines:
            print (line, end ='')
    except:
        print('File not found')


Output: 
 

Eighth line
Ninth line
Tenth line

 



Similar Reads

Python - Convert simple lines to bulleted lines using the Pyperclip module
Pyperclip is the cross-platform Python module which is used for copying and pasting the text to the clipboard. Let's suppose you want to automate the task of copying the text and then convert them to the bulleted points. This can be done using the pyperclip module. Consider the below examples for better understanding. Examples: Clipboard Content :
2 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Reading an excel file using Python
One can retrieve information from a spreadsheet. Reading, writing, or modifying the data can be done in Python can be done in using different methods. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work. Here, we will see the different methods to read o
3 min read
Reading an excel file using Python openpyxl module
Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files.For example, users might have to go through thousands of rows and pick out a few handful of information to make small changes based on some criteria. Using Openpyxl module, t
3 min read
Reading and Writing JSON to a File in Python
The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Reading and Writing lists to a file in Python
Reading and writing files is an important functionality in every programming language. Almost every application involves writing and reading operations to and from a file. To enable the reading and writing of files programming languages provide File I/O libraries with inbuilt methods that allow the creation, updation as well and reading of data fro
4 min read
Reading .Dat File in Python
Python, with its vast ecosystem of libraries and modules, provides a flexible and efficient environment for handling various file formats, including generic .dat files. In this article, we will different approaches to reading and process .dat files in Python. your_file.dat 1.0 2.0 3.04.0 5.0 6.07.0 8.0 9.0Read .Dat File In PythonBelow are some of t
2 min read
How to skip rows while reading csv file using Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
Uploading and Reading a CSV File in Flask
Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article, let's upload a CSV (Comma-Separated Values) file and read the contents of the file o
3 min read
Reading specific columns of a CSV file using Pandas
CSV files are widely utilized for storing tabular data in file systems, and there are instances where these files contain extraneous columns that are irrelevant to our analysis. This article will explore techniques for selectively reading specific columns from a CSV file using Python. Let us see how to read specific columns of a CSV file using Pand
3 min read