Locating Relative Resource Files

Peter Hansen peter at engcorp.com
Thu Sep 13 05:43:48 CEST 2001


Gordon McMillan wrote:
> 
> Don Garrett wrote:
> 
> >   Is there some way to determine the location of the file from which
> > the currently executing source was loaded? Or the file/directory of
> > the initial python script?
> 
> os.path.dirname(sys.argv[0]) should do it (although it may be '',
> meaning os.getcwd() is the script's directory).

I think this is close to being a FAQ.  The last time it came up,
I think we settled on:

   os.path.abspath(sys.argv[0])

Looking at abspath() in the module index, it says on most platforms
it is equivalent to os.path.normpath(os.path.join(os.getcwd(), <<path>>))
If sys.argv[0] specifies an absolute path, that expression just
returns sys.argv[0].  If it is relative, it is converted to absolute
by joining with the current directory.

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list