yalpsid eman
yalpsid eman

Reputation: 3452

Find location of directory 'x' number of directories up

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

Answers (2)

Thierry Lathuille
Thierry Lathuille

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

smeso
smeso

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

Related Questions