. Advertisement .
..3..
. Advertisement .
..4..
I don’t know how to handle the error filenotfounderror errno 2 no such file or directory.
In the code below, I’ll be utilizing the OS module and the os.listdir()
function to obtain a list of the files in the provided folder.
import os
for f in os.listdir("/etc"):
print(f)
However, you can see that Python throws this error:
Traceback (most recent call last):
File "Main.py", line 2, in <module>
for f in os.listdir("/etc/test"):
FileNotFoundError: [Errno 2] No such file or directory: '/etc/test'
Please tell me the cause of the problem and how to fix it as quickly as possible. Thanks.
The cause: If a relative path is used, the file will be checked in the present working directory instead of the original path. That is why Python is unable to identify the path of the file that you are referring to.
Solution: The way to deal with the error “FileNotFoundError: [Errno 2] No such file or directory”.
To make sure it’s pointing to the right directory, you should use an absolute path rather than a relative one.
You will get correct output: