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?
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