FileNotFoundError [Errno 2] No such file or directory error occurs when you try to access or import the file that does not exist in the specified location. The error can easily be solved by specifying the correct location of the file. As the error clearly mentioned “No such file or directory” which means the file that we are trying to access or the directory is not found. In this short article, we will learn how we can solve FileNotFoundError: [Errno 2] No such file or directory error using various methods. Moreover, we will also discuss how to understand errors in Python.
Solve FileNotFoundError [Errno 2] No such file or directory
The FileNotFoundError: [Errno 2] No such file or directory error occurs when we tried to access or import the Python file from the directory that does not exist. The reason can be either that we have provided the wrong directory or an incorrect file name. In both cases, we will get the FileNotFoundError: [Errno 2] No such file or directory error.
As we want to access main.txt file from the directory which is not there.
# opening the main.txt file
with open('main.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
# printing the lines
print(lines)
Output:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
/tmp/ipykernel_84359/181862891.py in <module>
1 # opening the main.txt file
----> 2 with open('main.txt', 'r', encoding='utf-8') as f:
3 lines = f.readlines()
4
5 # printing the lines
FileNotFoundError: [Errno 2] No such file or directory: 'main.txt'
Notice that we got the error saying that such a file or directory is not available because the main.txt file does not exist in the directory.
Move the File to the Same Directory
One of the simplest ways to solve the issue is to move the file to the same directory where the Python file exists and then use the above method to open the file again.
The above are the files in the same directory. We can easily open the file.txt using the open method as shown below:
# opening the main.txt file
with open('file.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
# printing the lines
print(lines)
Output:
['This is Bashir']
Notice that because the file was in the same directory, we didn’t get FileNotFoundError: [Errno 2] No such file or directory error while accessing the file.
Using an Absolute Path
An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words, we can say the absolute path is a complete path from the start of the actual filesystem from the / directory.
The absolute path can be found using the PWD command. Open the terminal and type the following commands:
pwd
One thing to notice is that you should open the terminal in the same directory where the txt file exists.
Now, we can use the above absolute path to access the file as shown below:
# opening the file.txt file using absolute path
with open('/home/student/Documents/Machine_Learning_Staff/Techfor-Today/Mixed-AI/file.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
# printing the lines
print(lines)
Output:
['This is Bashir']
As you can see, we got the output without getting any errors:
Alternative Methods to Get Absolute Path
In Python, there are other ways to get the absolute path as well. For example, we can use the os module to find the current directory of the file.
The os.getcwd method returns the current directory while the os.listdir returns a list that contains the names of the entries in the directory of the specific path.
# importing the os module
import os
# getting the directoyr
path = os.getcwd()
with open(path+'/file.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
# printing the lines
print(lines)
Output:
['This is Bashir']
Notice that we opened the file without getting FileNotFoundError: [Errno 2] No such file or directory error.
Using Relative Path
Now, let us assume that we have a folder located in the same directory and the text file is inside the folder. In such case, we can use the foldername/filename to access the file using the open function as shown below:
# using relative path
with open(newfolder/file.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
# printing the lines
print(lines)
Output:
['This is Bashir']
Or in another case, let us say that the folder is not in the same directory. If the structure of the directory is as shown below:
|__Folder
|___file.txt
|__PythonFile
|___python.py
As you can see, the python file and text file are in different folders. In such a case, we can also use the relative path as shown below to access the file.txt file from the python.py.
with open('../Folder/file.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
# printing the lines
print(lines)
Output:
['This is Bashir']
As you can see, we got access to the file using a relative path in Python.
Using Try-except Block
The try and except block in Python is used to handle errors. We can use the try-except block to check if the file or the directory is correct. The code inside the try block will be executed first and if any error occurs, then instead of crashing the code, the code inside the except block will be executed.
Here is how we can use it:
try:
with open('folder/file.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
except:
print("There is a problem in the file name or path")
Output:
There is a problem in the file name or path
As you can see, without getting errors or crashing the script, we handled the error. There was no such directory available in the system but still, we managed to save the code from crashing by specifying a message in the except block.
Understanding FileNotFoundError: [Errno 2] No such file or directory error
In Python usually, the errors give much more information and can be easily understood. The error has usually two parts. The first part shows the category which in this case is FileNotFoundError which means that there is a problem with the file. The second part of the error gives more specific information about the file which says either the directory is incorrect or the path is:
The following are some of the main reasons for FileNotFoundError: [Errno 2] No such file or directory error:
- The file does not exist in the directory
- The directory does not exist
- The file name is mistyped
- The directory is mistyped
How to Get the Path of the File in Python?
There are various methods available in Python to get the path of the current directory of the file that we want to know. Here we will discuss some of the methods that are commonly used to find the file name or directory.
Using Path.cwd()
The CWD stands for the current working directory and is used to find the path of the current directory of the Python file.
from pathlib import Path
print(Path.cwd())
Using os.getcwd()
Another method is to use the OS library to get the path of the current directory in Python. We can use the getcwd() method in order to find the current directory of the Python file.
import os
print( os.getcwd())
Using pathlib.path() method
The pathlib module can also help us to get access to the absolute path of the file. Here is how it works:
import pathlib
# current working directory
print(pathlib.Path().absolute())
There are other many methods also available but these are some of the very common ones used to find the directory of the file or current working area.
Summary
This short article discussed how we could solve FileNotFoundError: [Errno 2] No such file or directory error. We used five different methods to solve the FileNotFoundError: [Errno 2] No such file or directory error. Moreover, we also discussed the reasons for getting this error: