Reputation: 3452
Let's say I have a root directory 'x' number of directories up from the current directory. How can I find the full path to this root directory in python assuming 'x' can change and thus can't be hard-coded in any way?
Upvotes: 1
Views: 36
Reputation: 24233
You can use pathlib:
from pathlib import Path
levels_up = 1 # or whatever you want
current_dir = Path.cwd()
root = current_dir.parents[levels_up - 1]
print(root)
# /home <-- one level up from my home directory
Upvotes: 1
Reputation: 4295
from os.path import abspath, join
def get_root(path, up_n):
return abspath(join(path, join(['..'] * up_n)))
You might also consider using realpath
instead of abspath
, that will take care of resolving symbolic links too.
Upvotes: 0