programming-examples/python/Input_Output/Python program to read last n lines of a file.py

19 lines
754 B
Python
Raw Normal View History

2019-11-15 12:59:38 +01:00
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',2)