get directory name of file being executed

Skip Montanaro skip at pobox.com
Thu Feb 27 09:44:06 EST 2003


    David> I'm doing this:

    David> /usr/bin/python2 /some/script/in/a/dir/foo.py

    David> I want to get "/some/script/in/a/dir/", not the cwd of where I
    David> launched the script from.

    David> Is that possible?

Inside foo.py you have a global variable __file__.  Extract its directory:

    >>> __file__
    '/Users/skip/.python.py'
    >>> import os
    >>> os.path.dirname(__file__)
    '/Users/skip'

The above is from an interactive session, but the same holds true from
within any module.

Skip





More information about the Python-list mailing list