Home »
Python
Python | Example of FileNotFoundError
In this tutorial, we are going to learn how to catch the exception FileNotFoundError if file does not exist in the memory?
Submitted by IncludeHelp, on December 30, 2018
Python FileNotFoundError
"FileNotFoundError" - This is an exception in python and it comes when a file does not exist and we want to use it.
So in the below example, we will learn how to use and handle "FileNotFoundError"? Here, we are writing the code within with try statement.
Example 1 (FileNotFoundError exception)
Here, we are trying to open a file named "myfile.txt" which does not exist in the memory and handling the exception by using its name.
# trying to open a file, which does not exist
try:
#trying to open a file in read mode
fo = open("myfile.txt","rt")
print("File opened")
except FileNotFoundError:
print("File does not exist")
except:
print("Other error")
Output
File does not exist
Example 2 (Other exception)
Here, I am just writing "fopen" instead of "open" which is an error in python because there is no such function named "fopen".
# trying to open a file, which does not exist
try:
#trying to open a file in read mode
fo = fopen("myfile.txt","rt")
print("File opened")
except FileNotFoundError:
print("File does not exist")
except:
print("Other error")
Output
Other error