Finding the path to a file

Trent Mick trentm at ActiveState.com
Mon Aug 11 19:45:17 EDT 2003


[Todd Johnson wrote]
> So basically, I want to know how to find the directory
> my script is in, even when it is invoked from another
> directory. Any help would be greatly appreciated.

The __file__ global is there for that. Note that in some versions of
Python (<= 2.2 maybe) __file__ was not defined with
__name__=="__main__". If you are running one of these versions of Python
then add this snippet in your module:
    
    if __name__ == "__main__":
        import sys
        __file__ = sys.argv[0]

    # __file__ is now the fullpath to your script

Cheers,
Trent

-- 
Trent Mick
TrentM at ActiveState.com





More information about the Python-list mailing list