我正在寻找一种从给定目录中向上移动 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 个目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在 Python 中将货币字符串转换为浮点数?How do I convert a currency string to a floating point number in Python?(如何在 Python 中将货币字符串转换为浮点数?)
在 Pandas 中解析多索引 Excel 文件Parsing a Multi-Index Excel File in Pandas(在 Pandas 中解析多索引 Excel 文件)
pandas 时间序列 between_datetime 函数?pandas timeseries between_datetime function?( pandas 时间序列 between_datetime 函数?)
pandas 重新采样到每月的特定工作日pandas resample to specific weekday in month( pandas 重新采样到每月的特定工作日)
Python - 如何标准化时间序列数据Python - how to normalize time-series data(Python - 如何标准化时间序列数据)
statsmodels 使用 ARMA 模型进行预测statsmodels forecasting using ARMA model(statsmodels 使用 ARMA 模型进行预测)