Write A Python Function To Read An Entire Text File

Define a function  that takes the filename as an input argument and then open the file in read mode.  read the entire file and store it into a variable and prints it on the console

You can also  return the contents of the data as a  function return value

 

Write A Python Function To Read An Entire Text File



Write A Python Function To Read An Entire Text File

First define a function read file, Function takes the name of the file as an input argument,  use the try block to open the file in read mode and store the file descriptor.

In the expected block handle file not found error. Print appropriate error message and exit the program.

In the else block read the contents of the file and store or  return the content of the file.

def readfile(filename):
   try:
       fd_read = open(filename, "r")
   except FileNotFoundError:
       print("File is not present in directory")
   else:
       data = fd_read.read()
       print(data)




In the main program take a variable and ask the user to enter the file name using input function call. Once we get the file name as a input cal the read file function by passing the  filename as input argument

fname = input("Enter the filename : ")
readfile(fname)




Full program
=====================

def readfile(filename):
   try:
       fd_read = open(filename, "r")
   except FileNotFoundError:
       print("File is not present in directory")
   else:
       data = fd_read.read()
       print(data)


fname = input("Enter the filename : ")
readfile(fname)




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

Enter the filename : sample.txt
The file contains xyz
ABC DEF




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

C:\Users\Public\vlogs>python main.py
Enter the filename : first.c
#include <stdio.h>

int main(): {
    return 0;
}


C:\Users\Public\vlogs>dir
 Directory of C:\Users\Public\vlogs

18-12-2022  14:22    <DIR>          .
18-12-2022  14:22    <DIR>          ..
18-12-2022  14:23                55 first.c
18-12-2022  14:22               273 main.py
               2 File(s)            328 bytes
               2 Dir(s)  389,074,526,208 bytes free

C:\Users\Public\vlogs>
C:\Users\Public\vlogs>python main.py
Enter the filename : C:\Users\Public\vlogs\first.c
#include <stdio.h>

int main(): {
    return 0;
}


C:\Users\Public\vlogs>




Write A Python Function To Read An Entire Text File and Returns it

Full Program
==============

def readfile(filename):
   try:
       fd_read = open(filename, "r")
   except FileNotFoundError:
       print("File is not present in directory")
   else:
       return fd_read.read()


fname = input("Enter the filename : ")
data = readfile(fname)
print("Contents of file is ...")
print(data)





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

Try to run the above program and provide the filename as input to the program.

Provide the absolute path as well as relative path and see the difference.



Post a Comment

0 Comments