Python Exception Handling FileNotFoundError

By | August 13, 2019

Task: Python Exception Handling FileNotFoundError – This Python programming tutorial covers an code example of the Python Exception Handling.  If the FileNotFoundError exception occurs, this Python program will handle it gracefully by showing a simple and easy to understand error message.

"<yoastmark

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()

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 if FileNotFoundError ocurs

Sorry file not found

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

Leave a Reply

Your email address will not be published. Required fields are marked *