How to fix FileNotFoundError: Errno 2 no such file or directory
The FileNotFoundError: [Errno 2] No such file or directory error occurs when Python can’t find the specified file in the current directory.
Here’s an example:
import csvwith open('employee.csv','r') as file:employee = csv.reader(file)print(employee)
There are several reasons why the FileNotFoundError: [Errno 2] No such file or directory error can occur due to the following reasons:
Misspelled file name
If the file name is misspelled, the program assumes that the specified file doesn’t exist in the current directory, leading to the FileNotFoundError: [Errno 2] No such file or directory error. So, it’s always a good practice to recheck the file name.
Wrong directory
If the specified file doesn’t exist in the current directory, it leads to the FileNotFoundError: [Errno 2] No such file or directory error. This is called relative path and is the most common reason for the occurrence of this error.
Solution
To solve the issue, use the following code to check if the file exists in the current directory:
name, age, genderJohn, 23, MJake, 24, MJohnny, 22, M
If the desired file doesn’t exist, we can either add the file to the current directory or move the code file to the directory where the file resides.
We can also provide an absolute path, such as the Users/Documents/employee1.csv path. This will search for the file in the entire path we add.
Free Resources