Write a Python Function to Read And Print The First n Lines of a File

Given a filename  and the number of lines to be printed as an input to the Python function the Python function should try opening the file name.  Read the lines present in the file and then using the for loop just print a number of lines as an output  of the program.

This task should be done using a python function

 

Write a Python Function to Read And Print The First n Lines of a File

 

 

Write a Python Function to Read And Print The First n Lines of a File

let's define a function named print_lines() by passing the file name and n that is the number of lines to be printed from the file. using the try block try opening the file and get a file descriptor if the file is not found then catch and file not found exception.

def print_lines(filename, n):
   try:
       fd_read = open(filename, "r")
   except FileNotFoundError:
       print("The file you entered does not exists !!!")




Using the else part of the try block try reading all the lines from a file using a readlines function call and then using the follow iterate the only and required lines from the the file and print them as a output

   else:
       lines = fd_read.readlines()
       for line in lines[:n]:
           print(line, end="")




In the main program take a  variable filename and the number ask user to enter the file name and the number of lines to be printed.  using the print statement print the user-friendly message that is number of lines in a file are…

Then call the function print_lines  by passing the find them and that number of lines accepted from the user to the function of the input argument.

fname = input("Enter The File Name : ")
number = int(input("Enter the number of lies to be printed : "))
print(f"{number} lines of {fname} are ...")
print_lines(fname, number)






Final program
=================


def print_lines(filename, n):
   try:
       fd_read = open(filename, "r")
   except FileNotFoundError:
       print("The file you entered does not exists !!!")
   else:
       lines = fd_read.readlines()
       for line in lines[:n]:
           print(line, end="")


fname = input("Enter The File Name : ")
number = int(input("Enter the number of lies to be printed : "))
print(f"{number} of lines of {fname} are ...")
print_lines(fname, number)





Input to the program : contents of sample.txt
=====================================

Write
Python
Function
Read
 Print
  The
   First
    Lines
    File






Output
=============

Enter The File Name : sample.txt
Enter the number of lies to be printed : 4
4 lines of sample.txt are ...
Write
Python
Function
 Read




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

Execute the above program by providing the file name as an input argument to the function and number of lines you have to print.

Try with the absolute path and the relative path find the difference.





Post a Comment

0 Comments