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'):
print(f)
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.
Possible Causes
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.
Solutions
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:
apt
bootstrap.log
journal
fontconfig.log
wtmp
lastlog
postgresql
sysstat
unattended-upgrades
btmp
dpkg.log
alternatives.log
Conclusion
In this article, we discussed how to resolve the Python No Such File Or Directory error and how to resolve it.
Happy coding!!