How to move up n directories in Pythonic way?(如何以 Pythonic 方式向上移动 n 个目录?)
问题描述
我正在寻找一种从给定目录中向上移动 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 个目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何以 Pythonic 方式向上移动 n 个目录?


基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01