This tutorial will discuss the various scenarios where this type of error occurs, possible causes, and solutions to fix them.”
Python FileNotFoundError: [Errno 2] No Such File Directory
The best way to examine this type of error is to look at the first block of the error message.
Any error that starts with the FileNotFoundError block means that Python cannot find the file specified.
This forces Python to terminate as it cannot process the preceding code without accessing the specified file.
It is a built-in exception that is raised by the OS module when a requested file or directory does not exist. You can also raise this error manually, but that’s an article for another day.
NOTE: This error is not raised in operations such as creating new files or writing content to a file that does not exist,
Let us take an example code that will throw the FileNotFoundError.
for f in listdir('/non_existing_dir'):
in the example above, we start by importing the listdir function from the os module. Next, we print each file in the specified directory of the listdir() function.
Since the target directory does not exist, Python will return an error as:
FileNotFoundError: [WinError 3] The system cannot find the path specified: ‘/non_existing_dir’
FileNotFoundError: [Errno 2] No such file or directory: '/non_existing_dir'
As you can see, the code fails to execute as Python cannot find the set directory.
There are three major causes of the FileNotFoundError in Python.
- The directory or filename has been misspelled.
- Incorrect file path or directory path
- Use of relative paths.
The solutions are simple.
- Ensure that the full filename and directory name are spelled correctly, including the extension.
- Second, always make sure that the path you are specifying exists and is accessible.
- Python will not resolve relative paths. For example, instead of using the tilde (~) to specify your home directory, use the absolute path as /home/username.
In our example above, we can resolve the FileNotFoundError by creating the target directory as:
We can then re-run the code as shown:
The program should return the files and directory in that directory as:
In this article, we discussed how to resolve the Python No Such File Or Directory error and how to resolve it.