FileNotFoundError Exception in Python

By Lenin Mishra

This is the part of the 9th day in the Python 30 series. Check out the series here.

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.

  1. Try, Except, Else and Finally in Python
  2. ZeroDivisionError Exception in Python
  3. OverflowError Exception in Python
  4. ArithmeticError Exception in Python
  5. KeyError Exception in Python
  6. IndexError Exception in Python
  7. LookupError Exception in Python
  8. TypeError Exception in Python
  9. StopIteration Exception in Python
  10. NameError Exception in Python
  11. Catch Multiple Exceptions in Python