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:

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
def LastNlines(fname, N):
with open (fname) as file :
for line in ( file .readlines() [ - N:]):
print (line, end = '')
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
import os
def LastNlines(fname, N):
bufsize = 8192
fsize = os.stat(fname).st_size
iter = 0
with open (fname) as f:
if bufsize > fsize:
bufsize = fsize - 1
fetched_lines = []
while True :
iter + = 1
f.seek(fsize - bufsize * iter )
fetched_lines.extend(f.readlines())
if len (fetched_lines) > = N or f.tell() = = 0 :
print (''.join(fetched_lines[ - N:]))
break
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
def LastNlines(fname, N):
assert N > = 0
pos = N + 1
lines = []
with open (fname) as f:
while len (lines) < = N:
try :
f.seek( - pos, 2 )
except IOError:
f.seek( 0 )
break
finally :
lines = list (f)
pos * = 2
return lines[ - N:]
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!