w3resource logo

:

Python Exercises

Python File I/O: Read last n lines of a file

Python File I/O: Exercise-4 with Solution

Write a Python program to read last n lines of a file.

Sample Solution:-

Python Code:

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)

Sample Output:

Append this text.                                                                                             
Append this text.

Python Code Editor:

Improve this sample solution and post your code through Disqus