w3resource

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.

Flowchart:

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

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to append text to a file and display the text.
Next: Write a Python program to read a file line by line and store it into a list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/file/python-io-exercise-4.php