【问题标题】:Extract directories from a list of paths从路径列表中提取目录
【发布时间】:2014-03-07 13:23:35
【问题描述】:

我有一个文件路径列表,如下所示:

paths = [
    'A/B/b.py',
    'A/B/C/c1.py',
    'A/B/C/c2.py',
    'M/N/O/o1.py',
    'M/N/O/o2.py',
    'M/N/P/p1.py',
    'M/N/P/p2.py',
    'M/N/P/R/r2.py'
]

我想把它转换成这样的目录列表:

only_dirs = [
    'A',
    'A/B',
    'A/B/C',
    'M',
    'M/N',
    'M/N/O',
    'M/N/P',
    'M/N/P/R',
]

磁盘上不存在这些路径,它们只是从数据库收集的字符串,我想获取目录列表,以便根据路径中的任何目录过滤文件。这样做最干净的方法是什么?

【问题讨论】:

    标签: python string path


    【解决方案1】:
    result = set()
    for items in paths:
        splitted = items.split("/")[:-1]
        for idx in xrange(1, len(splitted) + 1):
            result.add("/".join(splitted[:idx]))
    
    only_dirs = sorted(result)
    print only_dirs
    

    输出

    ['A', 'A/B', 'A/B/C', 'M', 'M/N', 'M/N/O', 'M/N/P', 'M/N/P/R']
    

    【讨论】:

    • 我会使用 os.path.dirname(), os.path.split() 让它跨平台。
    • @LaurIvan 正确,但 OP 在问题中说 Those paths don't exist on the disk, they're just strings collected from DB :)
    • @thefourtheye,afaik 这些不检查路径的物理存在。您的解决方案是正确的,因为在 Windows 上使用 os.path 调用可能会产生错误的结果(尽管测试起来会很有趣)...
    【解决方案2】:

    编辑答案

    正如 thefourtheye 在评论中指出的那样,我的第一个答案是不正确的。

    这里有一个新的解决方案:

    only_dirs = []
    
    for path in paths:
        current = path[:path.rfind('/')]
        while len(current) > 0:
            if current not in only_dirs:
                only_dirs.append(current)
            current = current[:current.rfind('/')]
    
    only_dirs.sort()
    print only_dirs
    

    【讨论】:

    • 这会产生['A/B', 'A/B/C', 'A/B/C', 'M/N/O', 'M/N/O', 'M/N/P', 'M/N/P', 'M/N/P/R'],这不是 OP 所期望的。
    猜你喜欢
    • 1970-01-01
    • 2012-03-05
    • 2011-09-24
    • 2011-09-01
    • 1970-01-01
    • 2011-04-24
    相关资源
    最近更新 更多