如何以Python方式上移n个目录? [英] How to move up n directories in Pythonic way?
问题描述
我正在寻找一种从给定目录上移n
目录的pythonic方法.
I'm looking for a pythonic way to move up n
directories from a given directory.
假设我们有示例路径/data/python_env/lib/python3.6/site-packages/matplotlib/mpl-data
.如果要上移n=2
目录,则应该以/data/python_env/lib/python3.6/site-packages
结尾.
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
.
以下方法可将n
目录上移:
The following works to move up n
directories:
up_n = lambda path, n: '/'.join(path.split('/')[:-n])
但是,它不是很可读,并且在Windows计算机上的路径失败.从本质上讲,它并不是一个非常Python的解决方案.
However, it's not very readable and fails for paths on windows machines. In essence, it doesn't feel a very pythonic solution.
是否有更好的,更Python化的解决方案,也许使用os
模块?
Is there a better, more pythonic solution, maybe using the os
module?
推荐答案
您可以使用标准库的pathlib 模块:
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
这篇关于如何以Python方式上移n个目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!