Sometimes, we want to reliably open a file in the same directory as the currently running script with Python.
In this article, we’ll look at how to reliably open a file in the same directory as the currently running script with Python.
How to reliably open a file in the same directory as the currently running script with Python?
To reliably open a file in the same directory as the currently running script with Python, we can get the current folder of the script and then use open
with it.
For instance, we write
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
f = open(os.path.join(__location__, 'bundled-resource.jpg'))
to get the current location of the script with
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
We get the current directory with getcwd
.
And we get the relative path to the current script with
os.path.dirname(__file__)
Then we call os.path.realpath
to get the real path from the joined path to get the path of the current directory.
Then we call open
with the __location__
path we created.
Conclusion
To reliably open a file in the same directory as the currently running script with Python, we can get the current folder of the script and then use open
with it.