How to Resolve OSError: [Errno 2] No Such File or Directory in Python
-
the
OSError: [Errno 2] No Such File or Directory
in Python -
Resolve the
OSError: [Errno 2] No Such File or Directory
in Python
When running a program in Python, we often face errors. This article will discuss the OSError: [Errno 2] No such file or directory
in Python.
the OSError: [Errno 2] No Such File or Directory
in Python
This OSError: [Errno 2] No such file or directory
is generated by the OS library. This error happens when the file or directory we try to access is unavailable.
It happens because of two significant reasons. Either the file or folder we try to open does not exist, or we are entering the wrong path of that file or folder.
Python raises this error to inform the user that it cannot execute the program further without accessing the file referred to in the program. In Python version 3, we get the FileNotFoundError: [Errno 2] No such file or directory
.
This error is a sub-class of the OSError
, and we run this code on Ubuntu OS.
Example Code:
# Python 3.x
import os
import sys
os.chdir(os.path.dirname(sys.argv[0]))
We get the output below when we run the script using python mycode.py
.
Output:
#Python 3.x
Traceback (most recent call last):
File "mycode.py", line 3, in <module>
os.chdir(os.path.dirname(sys.argv[0]))
FileNotFoundError: [Errno 2] No such file or directory: ''
Resolve the OSError: [Errno 2] No Such File or Directory
in Python
When we don’t specify a path, sys.argv[0]
accesses mycode.py
and os.path.dirname
cannot determine the path. We can run the following script to solve the error using the command python ./mycode.py
.
# Python 3.x
import os
import sys
os.chdir(os.path.dirname(sys.argv[0]))
print("Hello")
Output:
#Python 3.x
Hello
An alternative way to resolve this error is to write the above code in the following manner. Because sys.argv[0]
is only a script name and not a directory, therefore os.path.dirname()
returns nothing.
That is converted into a correct absolute path with directory name using os.path.abspath()
. We run the following code using the command python mycode.py
.
# Python 3.x
import os
import sys
os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
print("Hello")
Output:
#Python 3.x
Hello
I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.
LinkedInRelated Article - Python Error
- Can Only Concatenate List (Not Int) to List in Python
- How to Fix Value Error Need More Than One Value to Unpack in Python
- How to Fix ValueError Arrays Must All Be the Same Length in Python
- Invalid Syntax in Python
- How to Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
- How to Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python