What's the simplest way to find the path to the file in which I am "executing" some code? By this, I mean that if I have a file foo.py
that contains:
print(here())
I would like to see /some/path/foo.py
(I realise that in practice what file is "being executed" is complicated, but I think the above is well defined - a source file that contains some function that, when executed, gives the path to said file).
I have needed this in the past to make tests (that require some external file) self-contained, and I am currently wondering if it would be a useful way to locate some support files needed by a program. But I have never found a good way of doing this. The inspect module sounds like it should work, but you seem to need a class or function that is defined in that module.
In particular, the module instances contain __file__
attributes, but I can't see how to get the "current" module. Objects have a __module__
attribute, but that's the module name, not a module instance.
I guess one way is to throw and catch an exception and inspect the contents, but that seems like hard work. Surely there is a simple, easy way that I have missed?
In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.
__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module. The updating and maintaining of this variable is the responsibility of the import system.
For getting the name of the Python script that is currently running you can use __file__. And if you want to remove the directory part which might be present with the name of the script, you can use os. path. basename(__file__).
Python source files are files that contain Python source code. As Python can be used as a scripting language, Python source files can be considered as scripts.
To get the absolute path of the current file:
import os
os.path.abspath(__file__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With