This tutorial will show you how to read last n lines from file using Python 3 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 we read file from the beginning but sometimes for our business requirements we may need to read a file from the end. So we 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.
Here in this example we will use Python 3.6 and you must understand the Python language to implement.
We define 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 we 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)
In the above output we get two lines because we wanted to print last 2 lines.
Download the sample text file from the link
Thanks for reading.Tags: file