import os
for dirpaths, dirnames, filenames in os.walk(mydir):
print dirpaths
给我所有(子)目录mydir
。如何仅获取树最底部的目录?
import os
for dirpaths, dirnames, filenames in os.walk(mydir):
print dirpaths
给我所有(子)目录mydir
。如何仅获取树最底部的目录?
这将仅打印出那些没有子目录的目录
for dirpath, dirnames, filenames in os.walk(mydir):
if not dirnames:
print dirpath, "has 0 subdirectories and", len(filenames), "files"
像这样?
for dirpaths, dirnames, filenames in os.walk(mydir):
if not dirnames: print dirpaths
我看到了两种显示叶目录的解决方案(即那些不包含子目录的解决方案)。另一方面,最底层的目录不仅是叶目录,而且处于最大深度。这是找出最底层目录的粗略方法:
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
import os
mydir='/home/'
print [dirpaths for dirpaths, dirnames, filenames in os.walk(mydir) if not dirnames]