Read Last n Lines From File Using Python

Read File

This tutorial will show you how to read last n lines from file using Python programming language. The last n lines means, last 5 lines or last 10 lines etc. So n can be replaced by any positive integer value.

Generally you read file from the beginning but sometimes for your business requirements you may need to read a file from the end. So you may need to read file from end using any technology. Here I will show you how to read last n lines from file using Python.

You may also read the similar tutorial on reading last n lines using Java and PHP.

Prerequisites

Python 3.8.5/3.11.5

Read Last n Lines

I have defined a function called tail() that takes three arguments – file name, number of lines to read from the end and block size in bytes.

The first argument, file name, is mandatory and others two are optional because I have provided default values for them.

def tail(file, n=1, bs=1024):
    f = open(file)
    f.seek(0,2)
    l = 1-f.read(1).count('\n')
    B = f.tell()
    while n >= l and B > 0:
            block = min(bs, B)
            B -= block
            f.seek(B, 0)
            l += f.read(block).count('\n')
    f.seek(B, 0)
    l = min(l,n)
    lines = f.readlines()[-l:]
    f.close()
    return lines

In the above tail() function, we use Python’s built-in seek() function that has the following features:

seek() sets the file’s current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file’s end. There is no return value.

The below line when calls the tail function prints the following output:

lines = tail("SampleTextFile_10kb.txt", 2)
for line in lines:
	print (line)

Output:

read last n lines python

In the above output we get two lines because we wanted to print last 2 lines.

Download the sample text file from the link.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *