Python成语获得与多次调用os.path.dirname相同的结果? [英] Python idiom to get same result as calling os.path.dirname multiple times?

查看:84
本文介绍了Python成语获得与多次调用os.path.dirname相同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己需要在源树中获取python文件的父目录,该源树是多个具有一定规律性的目录.不得不多次调用dirname很麻烦.

I find myself needing to get a parent directory of a python file in a source tree that is multiple directories up with some regularity. Having to call dirname many times is clunky.

我环顾四周,很惊讶地没有找到关于此的帖子.

I looked around and was surprised to not find posts on this.

一般情况是:

import os.path as op
third_degree_parent = op.dirname(op.dirname(op.dirname(op.realpath(__file__))))

是否有更惯用的方式来执行此操作,而无需嵌套的目录名调用?

Is there a more idiomatic way to do this that doesn't require nested dirname calls?

推荐答案

归一化相对路径; os.pardir 是父级目录,根据需要重复多次.也可以通过 os.path.pardir 来获得:

Normalize a relative path; os.pardir is the parent directory, repeat it as many times as needed. It is available via os.path.pardir too:

import os.path as op

op.abspath(op.join(__file__, op.pardir, op.pardir, op.pardir))

这篇关于Python成语获得与多次调用os.path.dirname相同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆