Reputation: 2879
I want to do join the current directory path and a relative directory path goal_dir
somewhere up in the directory tree, so I get the absolute path to the goal_dir
. This is my attempt:
import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
Now, if the current directory is C:/here/I/am/
, it joins them as C:/here/I/am/../../my_dir
, but what I want is C:/here/my_dir
. It seems that os.path.join
is not that intelligent.
How can I do this?
Upvotes: 52
Views: 101809
Reputation: 2879
Lately, I discovered pathlib.
from pathlib import Path
cwd = Path.cwd()
goal_dir = cwd.parent.parent / "my_dir"
Or, using the file of the current script:
cwd = Path(__file__).parent
goal_dir = cwd.parent.parent / "my_dir"
In both cases, the absolute path in simplified form can be found like this:
goal_dir = goal_dir.resolve()
Upvotes: 7
Reputation: 4182
consider to use os.path.abspath
this will evaluate the absolute path
or One can use os.path.normpath
this will return the normalized path (Normalize path, eliminating double slashes, etc.)
One should pick one of these functions depending on requirements
In the case of abspath
In Your example, You don't need to use os.path.join
os.path.abspath("../../my_dir")
os.path.normpath
should be used if you are interested in the relative path.
>>> os.path.normpath("../my_dir/../my_dir")
'../my_dir'
Other references for handling with file paths:
Upvotes: 12
Reputation: 473863
You can use normpath, realpath or abspath:
import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
print goal_dir # prints C:/here/I/am/../../my_dir
print os.path.normpath(goal_dir) # prints C:/here/my_dir
print os.path.realpath(goal_dir) # prints C:/here/my_dir
print os.path.abspath(goal_dir) # prints C:/here/my_dir
Upvotes: 63