Reputation: 1895
I am not looking for os.getcwd()
, since that seems to return your location at the moment you're executing the script.
If I am in /Users/jo/Documents/
, and I execute the script: /Users/scripts/python/myScript.py
, what can I execute from within my script, in order to check that /Users/scripts/python/siblingScript.py
exists?
So I was thinking that I would get the directory name of the file that's being executed first, and then call (...).exists("siblingScript.py")
on it.
How would I get this right?
Upvotes: 1
Views: 44
Reputation: 95522
Details are a little different depending on whether you're executing /Users/scripts/python/myScript.py
by its full path name or by a relative path. But in any case you can use functions in os.path. You probably want isfile()
rather than exists()
.
>>> import os.path
>>> p = os.path.dirname("/Users/scripts/python/myScript.py")
>>> p
'/Users/scripts/python'
>>> f = os.path.join(p, "siblingScript.py")
>>> f
'/Users/scripts/python/siblingScript.py'
>>> os.path.isfile(f)
True
If you're executing myScript.py by a relative path, use abspath().
>>> os.getcwd()
'/home/msherrill/test/Users/jo/Documents'
>>> p = os.path.dirname("../../scripts/python/myScript.py")
>>> p
'../../scripts/python'
>>> os.path.abspath(p)
'/home/msherrill/test/Users/scripts/python'
You should read the Python os.path docs specific to your version of Python. There are some application-specific, subtle details.
Upvotes: 1