3. Write a python program to read the last n lines of file, a.txt.
The output is:
Original file a.txt:
Welcome to
www.freelearningpoints.com
Expected Answer:
www.freelearningpoints.com
Sample Answer:
import sys import os def read_file(file_name,last_lines): buf_size = 8192 file_size = os.stat(file_name).st_size iter = 0 with open(file_name) as f: if buf_size > file_size: buf_size = file_size-1 data = [] while True: iter +=1 f.seek(file_size-buf_size*iter) data.extend(f.readlines()) if len(data) >= last_lines or f.tell() == 0: print(''.join(data[-last_lines:])) break read_file('a.txt', 1)
More Exercises:
Python String ExercisesMore Numpy Exercises:
Numpy String ExercisesMore Pandas Exercises:
Pandas Series ExercisesMore Tutorials:
Python Installation - Linux (Ubuntu)