FileNotFoundError Exception in Python

Learn to handle FileNotFound error in Python using try-except block.

FileNotFoundError Exception in Python
FileNotFound Error in Python

The FileNotFoundError Exception in Python is raised when you are trying to access a file or a directory that doesn’t exist.

Example 1

Code/Output

x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'

You can deal with such errors by using the FileNotFoundError Exception class.


Example 2

Code

try:
    x = open('random.txt')
except FileNotFoundError as e:
    print(f"FileNotFoundError successfully handled\n"
          f"{e}")

Output

FileNotFoundError successfully handled
[Errno 2] No such file or directory: 'random.txt'
The above code uses f-strings. Check out that article and other string formatting techniques.

Check out other Python Built-in Exception classes in Python.

built-in-exception-classes - Pylenin
A programmer who aims to democratize education in the programming world and help his peers achieve the career of their dreams.