Write a Python Program to Read The Last n Lines of a File

Given a filename and the number of lines to be read from the file,  you have to write a Python program to open the file and read the last lines from the file and print them on the console.

You have to follow these steps: open file,  read content,  and print last n lines

Let's try to  solve the Python program

 

 

Write a Python Program to Read The Last n Lines of a File

 


Write a Python Program to Read The Last n Lines of a File

Take  a variable named filename string type to store the name of the file and ask the user to enter the file name.  take another variable  type integer  to store the number of last lines to be printed.  use the input function to ask user to enter the file name and a number of last lines to be printed and convert them appropriately

filename = input("Enter the Filename : ")
line_numbers = int(input("Enter Number of Last Lines to be Printed : "))





Take another variable file descriptor to store the file descriptor of the file that is about to get open for reading purposes. Initialize the file descriptor to none

fd_read = None

 




Use that try expect block to open the file in a read word.  in the try block set the file descriptor after opening the file in read mode.  in the the expect use file not found error  to catch an exception, if the file is not found print the appropriate message and exit the program

try:
   fd_read = open(filename, "r")
except FileNotFoundError:
   print("File you entered is not found !")
   exit(-1)





Now use the else block to read the contents of the file and store it as a  list of lines by splitting the contents of the file using “\n”.

Use the for loop to iterate all the last line stored in lines variable and print each line.

else:
   lines = fd_read.readlines() [-line_numbers:]
   print(f"The last {line_numbers} lines of a file {filename} are …")
   for line in lines:
       print(line, end="")
   fd_read.close()





Full Python Program
=========================

filename = input("Enter the Filename : ")
line_numbers = int(input("Enter Number of Last Lines to be Printed : "))

fd_read = None
try:
   fd_read = open(filename, "r")
except FileNotFoundError:
   print("File you entered is not found !")
   exit(-1)
else:
   lines = fd_read.read().split("\n") [-line_numbers:]
   print(f"The last {line_numbers} lines of a file {filename} are …")
   for line in lines:
       print(line, end="")
   fd_read.close()




INPUT: Contents of sample.txt
==========================
happy
dog
was
unhappy
for
the
first
time

 



OUTPUT
==========================

Enter the Filename : sample.txt
Enter Number of Last Lines to be Printed : 3

The last 3 lines of a file tj.txt are …

the
first
time

 




The above program can also be written  using a with statement as shown below

Use the with statement to open the file,  read the contents of the file  using readlines()  function call,  and print the lines using a for loop

 



Final Program
=================

filename = input("Enter the Filename : ")
line_numbers = int(input("Enter Number of Last Lines to be Printed : "))

try:
   with open(filename, "r") as fd_read:
       lines = fd_read.readlines() [-line_numbers:]
   print(f"The last {line_numbers} lines of a file {filename} are …")
   for line in lines:
       print(line, end="")
except FileNotFoundError:
   print("File you entered is not found !")
   exit(-1)

 



Conclusion
==================

Try to run the program by providing the file name and the number of Lost lines to be read.



Comment down below if you have any suggestions or queries.

 

Post a Comment

0 Comments