Python 找到最深的嵌套路径?
有没有办法用python找到最深的嵌套路径 比如说如果你有一个目录列表,比如 /cats/xmas/1.jpg /猫/海滩/2.jpg /狗/xmas/2010/1.jpg 它会打印出来 /狗/xmas/2010/1.jpg 作为最长的路径Python 找到最深的嵌套路径?,python,directory,Python,Directory,有没有办法用python找到最深的嵌套路径 比如说如果你有一个目录列表,比如 /cats/xmas/1.jpg /猫/海滩/2.jpg /狗/xmas/2010/1.jpg 它会打印出来 /狗/xmas/2010/1.jpg 作为最长的路径 def longest_path( paths ): key = lambda path:path.count('/') return max(paths, key=key) 在计数之前,应在路径上使用 我想在Windows上这可能会有点棘
def longest_path( paths ):
key = lambda path:path.count('/')
return max(paths, key=key)
在计数之前,应在路径上使用
我想在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 ))
差不多
def longest_path( paths ):
key = lambda path:path.count('/')
return max(paths, key=key)
在计数之前,应在路径上使用
我想在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)
非常感谢各位 到目前为止,这似乎是可行的
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)
非常感谢各位 或者更快:key=lambda path:path.count'/'那么在传递到最长路径函数之前,我需要使用os.walk并附加到列表中吗?@Kevin Postal:你必须创建一个没有子文件夹的路径列表。@JochenRitzel,我想你的意思是?或者更快:key=lambda path:path.count'/'那么我需要使用os.walk并附加到列表中吗在传递到最长路径函数之前列出?@Kevin Postal:您必须创建一个没有子文件夹的路径列表。@JochenRitzel我想您的意思是?