How to Resolve OSError: [Errno 2] No Such File or Directory in Python

Fariba Laiq Feb 02, 2024
  1. the OSError: [Errno 2] No Such File or Directory in Python
  2. Resolve the OSError: [Errno 2] No Such File or Directory in Python
How to Resolve 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
Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

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.

LinkedIn

Related Article - Python Error