Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

How to fix FileNotFoundError Errno 2 no such file or directory

Sarvech Qadir

The error FileNotFoundError Errno 2 no such file or directory occurs when Python cannot find the specified file in the current directory.

Here is an example:

main.py
employee1.csv
import csv

with 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:

1. Misspelled filename

There may be times when your filename will have been misspelled. In such a case, the file you specified will not exist in the current directory. So, recheck your filename.

2. Wrong directory

There might be times when your files won’t not exist in the current directory. These are called relative paths and are the most usual occurrence of this error.

To solve the issue, use the following code to check if the file exists in the current directory:

main.py
employee1.csv
name, age, gender
John, 23, M
Jake, 24, M
Johnny, 22, M

If the desired file does not exist, you can then either add the file to the current directory or move your code file to the directory where the file resides.

You can also provide an absolute path such as Users/Documents/employee1.csv. This will search for the file in the path that you have stated.

RELATED TAGS

python

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring