【问题标题】:How can you avoid lots of os.pardir in a row when constructing upward paths using os.path.join?使用 os.path.join 构建向上路径时,如何避免连续出现大量 os.pardir?
【发布时间】:2016-05-27 03:51:56
【问题描述】:

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

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)

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

【问题讨论】:

标签: python python-2.7 path filesystems


【解决方案1】:

使用pathlib2(Python 3 标准库模块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'

【讨论】:

  • 不错。 pathlib2 是否保证可用,还是我必须安装它?
  • @GreenAsJade,您应该在 Python 2.x 中安装它。 Pytohn 3.4+ 内置。
  • 谢谢。在可能的情况下,这是一个很好的解决方案。不幸的是,我遇到了无法添加库的情况(长篇大论:))
【解决方案2】:

嘿 - 找到了方法。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 2022-01-24
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    相关资源
    最近更新 更多