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?
Use os. path.path. dirname(path) to go a folder up from path . Use os. chdir(path) to move to this new directory.
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.
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
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