使用os.path.join构建向上路径时,如何避免连续出现很多os.pardir?

How can you avoid lots of os.pardir in a row when constructing upward paths using os.path.join?

我正在努力避免这种事情:

sibling_location = os.path.join(leaf_dir, os.pardir, os.pardir, os.pardir, sibling_name)

我觉得这样说会很酷

sibling_location = os.path.join(leaf_dir, *[os.pardir]*3, sibling_name)

但不幸的是,* 参数扩展技巧不允许在它扩展的列表之后有更多的参数。

呵呵 - 找到方法了。

sibling_location = os.path.join(leaf_dir, *([os.pardir]*3 + [sibling_name]))

读起来不太好,但是很简洁。很高兴接受其他更好的答案:)

使用 pathlib2 (backport of Python 3 standard library module pathlib) 怎么样?

>>> leaf_dir = '/path/to/some/deep/deeper/leaf_dir'
>>> sibling_name = 's'
>>> 
>>> # Using os.path.join
>>> import os
>>> os.path.join(leaf_dir, *([os.pardir]*3 + [sibling_name]))
'/path/to/some/deep/deeper/leaf_dir/../../../s'
>>> os.path.normpath(os.path.join(leaf_dir, *([os.pardir]*3 + [sibling_name])))
'/path/to/some/s'
>>>
>>> # Using pathlib / pathlib2
>>> import pathlib2
>>> str(pathlib2.Path(leaf_dir).parents[2] / sibling_name)
'/path/to/some/s'