Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move up n directories in Pythonic way?

I'm looking for a pythonic way to move up n directories from a given directory.

Let's say we have the example path /data/python_env/lib/python3.6/site-packages/matplotlib/mpl-data. If we were to move up n=2 directories we should end up at /data/python_env/lib/python3.6/site-packages.

The following works to move up n directories:

up_n = lambda path, n: '/'.join(path.split('/')[:-n])

However, it's not very readable and fails for paths on windows machines. In essence, it doesn't feel a very pythonic solution.

Is there a better, more pythonic solution, maybe using the os module?

like image 766
jwalton Avatar asked Apr 04 '19 13:04

jwalton


People also ask

How do you go up a directory in Python?

Use os. path.path. dirname(path) to go a folder up from path . Use os. chdir(path) to move to this new directory.

How do I change directory in Python using CMD?

You can change the directory by just typing "cd DirectoryPath" into the command prompt. Replace "DirectoryPath" with either a full path or the name of a folder in the current folder to go into that folder. You can type "cd .." to "up" or "out of" the current directory.


1 Answers

You can use the pathlib module of the standard library:

from pathlib import Path

path = Path('/data/python_env/lib/python3.6/site-packages/matplotlib/mpl-data')

levels_up = 2
print(path.parents[levels_up-1])
# /data/python_env/lib/python3.6/site-packages
like image 159
Thierry Lathuille Avatar answered Oct 18 '22 19:10

Thierry Lathuille