FileNotFoundError
FileNotFoundError
is a built-in exception that occurs when an operation requires a file or directory that doesn’t exist in the specified location. It’s a subclass of OSError
designed to signal that the file or directory you’re trying to access couldn’t be found.
You can use this exception to handle cases where your code relies on external files or directories that might not be present. By handling the exception, you can provide a more user-friendly error message or take corrective actions, such as creating the missing file or directory.
FileNotFoundError
Occurs When
A file or directory doesn’t exist in the specified location.
FileNotFoundError
Can Be Used When
- Checking if a file exists before attempting to open it
- Providing a user-friendly message or prompt when a required file is missing
- Creating a file if it doesn’t exist when reading from or writing to it
- Logging detailed error messages for debugging when file operations fail
FileNotFoundError
Example
An example of when the exception occurs:
>>> with open("non_existent_file.txt", "r") as file:
... content = file.read()
...
Traceback (most recent call last):
...
FileNotFoundError: [Errno 2] No such file or directory: 'non_existent_file.txt'
An example of how to handle this exception:
>>> try:
... with open("non_existent_file.txt", "r") as file:
... content = file.read()
... except FileNotFoundError:
... print("The file you're trying to access doesn't exist.")
...
The file you're trying to access doesn't exist.
Related Resources
Tutorial
Reading and Writing Files in Python (Guide)
In this tutorial, you'll learn about reading and writing files in Python. You'll cover everything from what a file is made up of to which libraries can help you along that way. You'll also take a look at some basic scenarios of file usage as well as some advanced techniques.
For additional information on related topics, take a look at the following resources: