Skip to content Skip to sidebar Skip to footer

How To Get Full Path To Python Program Including Filename Within The Program?

I have a python program, and I want to get the path to the program from within the program, but INCLUDING the file name itself. The name of my file is PyWrapper.py. Right now I'm d

Solution 1:

Take a look at __file__. This gives you a filename where the code actually is.

Also, there's another option:

import __main__ as main
print(main.__file__)

This gives you a filename of a script being run (similar to what your argv does).

The difference comes into play when the code is imported by another script.

Solution 2:

print__file__

should work.

__file__ returns the path of the executed file

Solution 3:

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 inos.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.
printos.path.join(os.path.dirname(__file__), '..')

# The canonicalised (?) directory where the program resides.
printos.path.dirname(os.path.realpath(__file__))

# The absolute path of the directory where the program resides.
printos.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.

Solution 4:

try using __file__. as long as the module is ran from a file, i.e. not code in an editor, __file__ will be the abs path to the module!

print__file__

Or for command line.

def get_my_name():
    if __name__ == '__main__':
        returnos.path.abspath(os.path.join(os.curdir, __file__))
    else:
        return __file__.replace('.pyc', '.py')

Post a Comment for "How To Get Full Path To Python Program Including Filename Within The Program?"