【问题标题】:How can I get the pathname of the folder two directories upstream of a file?如何获取文件上游两个目录的文件夹的路径名?
【发布时间】:2016-05-31 23:42:33
【问题描述】:

使用 glob2 和 os 我想要目录 '/a/b/' 给定文件路径 '/a/b/c/xyz.txt'

我已经能够(递归地)在 glob2 中使用 /*/** 在目录中前进,但不能通过父目录后退。我不想使用正则表达式或拆分。有没有使用 glob 和/或 os 的简单方法?

【问题讨论】:

  • os.path.dirname(os.path.dirname("/a/b/c/xyz.txt")) ?
  • 虽然"/a/b/c/xyz.txt".rsplit("/",2)[0] 我真的推荐使用rsplit
  • 你是对的 - 我认为 rsplit 最有意义。它简洁明了,便于我以后阅读和理解。

标签: python glob


【解决方案1】:

为什么是全局?

dir_path = file_path.split('/')
what_i_want = '/' + dir_path[10] + '/' + dir_path[1] + '/'

您也可以通过查找第三个斜杠的索引来做到这一点,使用每个调用的返回作为下一个调用的“开始”参数。

third_slash = file_path.index('/', file_path.index('/', file_path.index('/')+1) +1)
what_i_want = file_path[:third_slash+1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 2014-04-21
    • 2014-11-05
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    相关资源
    最近更新 更多