找到最深的嵌套路径?

1 投票
2 回答
2594 浏览
提问于 2025-04-16 08:33

有没有办法用Python找到最深的嵌套路径呢?

比如说,如果你有一个文件夹的列表,像这样:

/cats/xmas/1.jpg
/cats/beach/2.jpg
/dogs/xmas/2010/1.jpg

那么它会输出

/dogs/xmas/2010/1.jpg

作为最长的路径。

2 个回答

1

到目前为止,这看起来是有效的。

import os,sys

list = []
search_path = 'C:\Users\\Kevin\\Desktop\\'

def nesting(path):
    """ counts how often `os.path.split` works on `path` """
    c = 0
    head = tail = path
    while head and tail:
        head, tail = os.path.split(head)
        c +=1
    return c

def longest_path( paths ):
        return max(paths, key=nesting)

for root, dirs, files in os.walk(search_path):
   for name in files:       
       filename = os.path.join(root, name)
       sys.stdout.write('.')
       list.append(filename)

print longest_path(list)

非常感谢你们,伙计们!

6

类似这样的内容:

def longest_path( paths ):
    key = lambda path:path.count('/')
    return max(paths, key=key)

在计算路径之前,你应该使用 os.path.normpath 来处理路径。

我想在Windows上这可能会有点麻烦,因为路径分隔符可以是 \ 或 / ... 下面的代码可以让 os.path.split 来自动判断:

import os.path
def nesting(path):
    """ counts how often `os.path.split` works on `path` """
    c = 0
    head = tail = path
    while head and tail:
        head, tail = os.path.split(head)
        c +=1
    return c

def longest_path( paths ):
        return max(paths, key=nesting)

因为你要找的是最深的路径,所以它必须是一个没有子文件夹的文件夹!你可以这样获取:

def find_leafes( root ):
    """ finds folders with no subfolders """
    for root, dirs, files in os.walk(root):
        if not dirs: # can't go deeper
            yield root

print longest_path(find_leafes( root ))

撰写回答