有没有办法用python找到最深的嵌套路径?
比如说,如果你有一个目录列表,比如
/猫/圣诞节/1.jpg /猫/海滩/2.jpg /dogs/xmas/2010/1.jpg
它会打印 /dogs/xmas/2010/1.jpg
最长的路径
请您参考如下方法:
有点像
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 ))
