How to Solve No Such File or Directory Error in Python
When you are trying to open a file for view or edit, you often face an error like No such file or directory. Let’s see how to solve that error.
Solved No Such File Or Directory Error in Python
To solve No Such File Or Directory Error in your Python code, make sure that the file exists in your provided path. To check all the files in the directory, use the os.listdir() method. The os.listdir() is a built-in Python method that lists the files in the current working directory.
There are two types of paths in Python.
- Absolute Path
- Relative Path
Absolute Path in Python
An absolute path always contains the root element and the complete directory list required to locate the file. If you pass the absolute path, then you won’t get No Such File Or Directory Error because you are providing the perfect filepath to that file.
If the file does not exist, you will get the error; otherwise, you won’t get any error because you are not looking at the wrong folder.
Absolute Path in Windows
Always use an absolute path to open the file.
file = open(r'C:\Users\krunal\index.php')
If you are not in the directory you want to open a file, change the current working directory before opening the file.
import os os.chdir(r'C:\Users\krunal\public_html') file = open('index.php')
Another common mistake that can cause the “file not found” error include:
Accidentally using escape sequences in a file path
path = 'C:\Users\newton\index.php'
This will generate an error. To avoid making this mistake, remember to use raw string literals for file paths:
path = r'C:\Users\newton\index.php'
Absolute Path in Linux
Relative Path in Python
A relative path needs to be combined with another path to access a file. A relative path is defined as the path related to the current working directly(cwd). It starts at your current directory and never starts with a / because it is not root.
A relative path in the programming is not recommended because the platforms are different, and sometimes it does not work as expected. That is why always pass the absolute path and ensure that the file you want to work with exists in your directory.
Relative Path in Windows
Relative Path in Linux
Make sure you’re in the directory you think you’re in with os.getcwd() (if you launch your code from an IDE, you may well be in a different directory).
Relative file paths are always relative to the current working directory, and the current working directory doesn’t have to be the location of your python script.
The relative path begins with a dot (period), representing the current directory (also called the “working directory”). The relative path ./public_html/index.php is valid only if the current directory contains a path named public_html which contains a directory named index.php.
That is it for solving the No Such File Or Directory Error in Python.