Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python joining current directory and parent directory with os.path.join

Tags:

python

os.path

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?

like image 704
Lewistrick Avatar asked Jun 25 '13 10:06

Lewistrick


People also ask

How do you join two paths in Python?

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.

How do I reference a parent directory in Python?

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.

What does os path Join mean?

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.

What does path (__ file __) parent do?

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.


1 Answers

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 
like image 118
alecxe Avatar answered Sep 27 '22 19:09

alecxe