Write A Python Script To Open And Read The File

Given the filename as input to the Python program you have to write a python script to open the file in the  read mode and then read the contents of the file and print it.

Let's use try and except block to check if a file exists or not.

 

 

Write A Python Script To Open And Read The File

 


Write A Python Script To Open And Read The File

Let's take a variable named filename to show the name of the file and using the input function call ask the user to enter a  filename as string.

filename = input("Enter a Filename : ")




Use that try block and using the open function call open the file name in the read mode if the file is found store the file descriptor as shown below.  if the file is not found using except block print an error message and exit the program.

Using the else block of try read the contents of the file descriptor in to variable named data and print it the as output of the Python script using print() function call

try:
   fd_read = open(filename, "r")
except FileNotFoundError:
   print("The File You Entered Does not Exists")
else:
   data = fd_read.read()
   print("The Contents of File is ... \n ")
   print(data)




Complete python script to open the file and read the contents
===============================

filename = input("Enter a Filename : ")

try:
   fd_read = open(filename, "r")
except FileNotFoundError:
   print("The File You Entered Does not Exists")
else:
   data = fd_read.read()
   print("The Contents of File is ... \n ")
   print(data)






Output of the program given input as main.py
=================

>python main.py
Enter a Filename : main.py
The Contents of File is ...

filename = input("Enter a Filename : ")

try:
   fd_read = open(filename, "r")
except FileNotFoundError:
   print("The File You Entered Does not Exists")
else:
   data = fd_read.read()
   print("The Contents of File is ... \n ")
   print(data)



Output of program provided input filename dummy.txt that does not exist in the directory
================================
>python main.py
Enter a Filename : dummy.txt
The File You Entered Does not Exists




Conclusion
==============
Execute the above python script by providing different files as an input to the python script note down the results.

Comment it down below if you have any suggestions to improve the more Python program

Post a Comment

0 Comments