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.
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.
import sys import os def file_read_from_tail(fname,lines): bufsize = 8192 fsize = os.stat(fname).st_size iter = 0 with open(fname) as f: if bufsize > fsize: bufsize = fsize-1 data = [] while True: iter +=1 f.seek(fsize-bufsize*iter) data.extend(f.readlines()) if len(data) >= lines or f.tell() == 0: print(''.join(data[-lines:])) break file_read_from_tail('test.txt',5)
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", 5)
for line in lines:
print (line)
Output:
In the above output we get five lines because we wanted to print last 5 lines.
No comments:
Post a Comment