Just in case you would like to find the absolute path for other files, not just the one you are currently running, in that same directory, a general approach could look like this:
import sys,os
pathname = os.path.dirname(sys.argv[0])
fullpath = os.path.abspath(pathname)
for root, dirs, files in os.walk(fullpath):
for name in files:
name = str(name)
name = os.path.realpath(os.path.join(root,name))
print name
As others are mentioning, you could take advantage of the __file__
attribute. You can use the __file__
attribute to return several different paths relevant to the currently loaded Python module (copied from another StackOverflow answer):
When a module is loaded in Python, file is set to its name. You can then use that with other functions to find the directory that the file is located in.
# The parent directory of the directory where program resides.
print os.path.join(os.path.dirname(__file__), '..')
# The canonicalised (?) directory where the program resides.
print os.path.dirname(os.path.realpath(__file__))
# The absolute path of the directory where the program resides.
print os.path.abspath(os.path.dirname(__file__))
Remember to be wary of where the module you are loading came from. It could affect the contents of the __file__
attribute (copied from Python 3 Data model documentation):
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__
attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.