有没有办法找到python最深的嵌套路径?找到最深的嵌套路径?
喜欢说,如果你有一个像
/cats/xmas/1.jpg /cats/beach/2.jpg目录列表 /dogs/xmas/2010/1.jpg
这将打印 /dogs/xmas/2010/1.jpg
为最长路径
有没有办法找到python最深的嵌套路径?找到最深的嵌套路径?
喜欢说,如果你有一个像
/cats/xmas/1.jpg /cats/beach/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))
到目前为止,这似乎是工作
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)
非常感谢你们!
然后你应该接受THC4k的回答 – 2010-12-15 01:38:03
甚至更快:key = lambda path:path.count('/') – Will 2010-12-15 01:11:59
@ will:thanks! – 2010-12-15 01:19:43
那么我需要使用os.walk并在传递给longest_path函数之前追加到列表中? – 2010-12-15 01:21:33