问题描述
我正在寻找一种从给定目录中向上移动 n
目录的 Python 方法.
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 机器上的路径会失败.本质上,感觉不是一个非常pythonic的解决方案.
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 标准库模块:
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
这篇关于如何以 Pythonic 方式向上移动 n 个目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!