Finding the path to a file

Robin Munn rmunn at pobox.com
Tue Aug 12 13:32:43 EDT 2003


Todd Johnson <overdrive_ss at yahoo.com> 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.

Basically, you want to use sys.argv[0] -- but make sure to call
os.path.abspath() on it first. Try this:

--- begin sample code ---
#!/usr/bin/python

import os, sys

print "sys.argv[0] is", sys.argv[0]
print "os.path.abspath(sys.argv[0]) is", os.path.abspath(sys.argv[0])

mypath, myname = os.path.split(os.path.abspath(sys.argv[0]))

print "Script name is", myname
print "Script path is", mypath
---- end sample code ----

I can run this in a variety of ways and get the same value for mypath:

--- begin transcript ---
[rmunn at localhost ~/tmp]$ ./test.py
sys.argv[0] is ./test.py
os.path.abspath(sys.argv[0]) is /home/rmunn/tmp/test.py
Script name is test.py
Script path is /home/rmunn/tmp
[rmunn at localhost ~/tmp]$ python test.py
sys.argv[0] is test.py
os.path.abspath(sys.argv[0]) is /home/rmunn/tmp/test.py
Script name is test.py
Script path is /home/rmunn/tmp
[rmunn at localhost ~/tmp]$ cd ..
[rmunn at localhost ~]$ python tmp/test.py
sys.argv[0] is tmp/test.py
os.path.abspath(sys.argv[0]) is /home/rmunn/tmp/test.py
Script name is test.py
Script path is /home/rmunn/tmp
[rmunn at localhost ~]$ python /home/rmunn/tmp/test.py
sys.argv[0] is /home/rmunn/tmp/test.py
os.path.abspath(sys.argv[0]) is /home/rmunn/tmp/test.py
Script name is test.py
Script path is /home/rmunn/tmp
---- end transcript ----

Hope this helps.

-- 
Robin Munn <rmunn at pobox.com> | http://www.rmunn.com/ | PGP key 0x6AFB6838
-----------------------------+-----------------------+----------------------
"Remember, when it comes to commercial TV, the program is not the product.
YOU are the product, and the advertiser is the customer." - Mark W. Schumann




More information about the Python-list mailing list