Python Exception Handling FileNotFoundError

By | August 13, 2019

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.

Python Exception Handling FileNotFoundError

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

    file1 = open("d:/mytext2.txt", "r")

except FileNotFoundError:
        print("Sorry file not found")
# Read all contents of text file in a string s

s =

# show the contents from string s


# close the text file

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


5 thoughts on “Python Exception Handling FileNotFoundError

  1. Pingback: Python File Copy Program using shutil.filecopy |

  2. Pingback: Python Text File Program To Count Vowels |

  3. Pingback: Python file program read numbers write squares |

  4. Pingback: Find Occurrences of Each Word in Text File Python Program |

  5. Pingback: Python Text File Read and Show File Contents |

Leave a Reply

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