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?
path. join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator ('/') following each non-empty part except the last path component.
Using os.os. path. abspath() can be used to get the parent directory. This method is used to get the normalized version of the path.
os. path. join combines path names into one complete path. This means that you can merge multiple parts of a path into one, instead of hard-coding every path name manually.
The path. parent() method, as the name suggests, returns the parent directory of the given path passed as an argument in the form of a string. Therefore, to get the parent directory of a path, we need to pass the path string to the path.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With