有没有办法用python找到最深的嵌套路径?
比如说,如果你有一个目录列表,如
/cats/xmas/1.jpg /cats/beach/2.jpg /dogs/xmas/2010/1.jpg
它会打印出来 /dogs/xmas/2010/1.jpg是最长的路径
答案 0 :(得分: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 ))
答案 1 :(得分: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)
非常感谢你们!