To fix FileNotFoundError: [Errno 2] No such file or directory error, check that you are referring to the right file or folder in your program. Here is an example scenario featuring a FileNotFoundError message.
An Example Scenario
We’re writing a program that lists all the files in a folder. The folder we are referencing contains a list of markdown documentation for our project. To start, let’s import the os library, which has a method that lets us see all the files in a folder:
import os
Next, we are going to use the os.listdir() method to get a list of the files in our folder:
for f in os.listdir("/home/james/python_error/documentation/"):
print(f)
We retrieve a list of the files in the “/home/james/python_error/documentation/” folder. The for statement iterates over each file that the os.listdir() method finds. We print the name of each file to the console. Let’s see what happens when we run our code:
FileNotFoundError: [Errno 2] No such file or directory:
'/home/james/python_error/documentation/'
The Solution
We have referenced a folder that does not exist. To solve the error in our program, we must make sure the directory to which we point exists. The actual folder with our docs is at /home/james/python_error/docs. Let’s change the folder to which our program refers to the one that actually contains our documentation:
import os
for f in os.listdir("/home/james/python_error/docs/"):
print(f)
index.md
The output from our command is what we expected. We can see there is one file in our folder. If we had other files in the /home/james/python_error/docs/ folder, we would be able to see them in the output of our program.