Finding the path to a file

Bengt Richter bokr at oz.net
Mon Aug 11 21:36:33 EDT 2003


On Mon, 11 Aug 2003 16:45:17 -0700, Trent Mick <trentm at ActiveState.com> wrote:

>[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
                           ^^^^
Well, not guaranteed. Try going to the script directory and typing 

    python myscript.py

I think you might need os.path.abspath(sys.argv[0]) # untested

Regards,
Bengt Richter




More information about the Python-list mailing list