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 个目录?
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 沿轴计算直方图 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- python-m http.server 443--使用SSL? 2022-01-01
