9
import os

for dirpaths, dirnames, filenames in os.walk(mydir):
    print dirpaths

给我所有(子)目录mydir。如何仅获取树最底部的目录?

4

4 回答 4

15

这将仅打印出那些没有子目录的目录

for dirpath, dirnames, filenames in os.walk(mydir):
    if not dirnames:
        print dirpath, "has 0 subdirectories and", len(filenames), "files"
于 2013-07-30T19:44:32.643 回答
4

像这样?

for dirpaths, dirnames, filenames in os.walk(mydir):
    if not dirnames: print dirpaths
于 2013-07-30T19:46:24.347 回答
2

我看到了两种显示叶目录的解决方案(即那些不包含子目录的解决方案)。另一方面,最底层的目录不仅是叶目录,而且处于最大深度。这是找出最底层目录的粗略方法:

import os

mydir = '/Users/haiv/src/python'
max_depth = 0
bottom_most_dirs = []
for dirpath, dirnames, filenames in os.walk(mydir):
    depth = len(dirpath.split(os.sep))
    if max_depth < depth:
        max_depth = depth
        bottom_most_dirs = [dirpath]
    elif max_depth == depth:
        bottom_most_dirs.append(dirpath)
print bottom_most_dirs
于 2013-07-30T20:09:49.013 回答
1
import os

mydir='/home/'
print [dirpaths for dirpaths, dirnames, filenames in os.walk(mydir) if not dirnames]
于 2018-05-22T16:20:59.320 回答