Task: Python Exception Handling FileNotFoundError – If the user enters a wrong name or path for the file, this program will handle it gracefully by showing a simple and easy to understand error message.
How To Handle FileNotFound Exception in Python?
We will use try-except block to handle FileNotFound exception.
Note that the try-block will have the code to be monitored for any exception. On the other hand the except-block will contain the code to handle the exception occured.
The Source Code – Python Read and Show File Program with Exception Handling
# Write a Python program to open # an existing file mytext.txt from # D drive. The program will read and show # the contents of this text file # on D drive. # the program will cover FileNotFoundError # through Python Exception Handling import sys # open mytext.txt file in read mode try: file1 = open("d:/mytext2.txt", "r") except FileNotFoundError: print("Sorry file not found") sys.exit() # Read all contents of text file in a string s s = file1.read() # show the contents from string s print(s) # close the text file file1.close()
Python Exception Handling FileNotFoundError
If we try to open a file for reading which does not exist
Then a FileNotFoundError exception occurs and we will display our user defined custom error message. We have also imported the sys module. This is beacause we will use sys.exit() function to terminate the Python program if exception occurs after displaying a suitable messae to the user.
The output:
Sorry file not found
This is a very simple example of a File handling program showing the occurrence of an error and to handle it gracefully using the Python code.
Why To Handle FileNotFound Exception?
This program may be written without handling the exception, but in this case, the program will terminate and will show default error message. The default messages may be hard to read and understand.
Therefore, we use the exception handling in this program.
You may also like to read:
Python File Programs – Python File Handling
Write a Python file program read numbers write squares.
Python Text File Read and Show Contents Program
Python Text File Read and Display file data with Exception Handling FileNotFoundError
Python File Program Count Characters in Text File
Python Text File Program To Count Vowels
Pingback: Python File Copy Program using shutil.filecopy | EasyCodeBook.com
Pingback: Python Text File Program To Count Vowels | EasyCodeBook.com
Pingback: Python file program read numbers write squares | EasyCodeBook.com
Pingback: Find Occurrences of Each Word in Text File Python Program | EasyCodeBook.com
Pingback: Python Text File Read and Show File Contents | EasyCodeBook.com