Find deepest nested path?
Is there a way to fi开发者_如何学Gond the deepest nested path with python?
Like say if you had a list of directories like
/cats/xmas/1.jpg /cats/beach/2.jpg /dogs/xmas/2010/1.jpg
it would print /dogs/xmas/2010/1.jpg
as being the longest path
Something like
def longest_path( paths ):
key = lambda path:path.count('/')
return max(paths, key=key)
You should use os.path.normpath
on the paths before counting.
I guess on Windows this could get a bit tricky since the path separator can be either \ or / ... the code below lets os.path.split
figure it out:
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)
Since you're looking for the deepest path, it has to be a folder that has no subfolders! You can get it like this:
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 ))
So far this seems to be working
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)
Thanks so much guys!
精彩评论