lowest_dirs = list()
for root,dirs,files in os.walk(starting_directory):
if not dirs:
lowest_dirs.append(root)
This works because os.walk
recurses through the directories, setting each to root
in turn. You want to know if it's a lowest-level directory? That means it contains no other directories, so for that root if dirs
is empty, toss it in an accumulator.
If you additionally want to skip EMPTY lowest-level folders, do:
if files and not dirs:
If you only want the tail (the folder name, not the whole path), use:
lowest_dirs.append(os.path.split(root)[-1])
Test it:
>>> lowest_dirs = list()
>>> toplevel = r"U:\User\adsmith\My Documents\dump\father_dir"
>>> for root,dirs,files in os.walk(toplevel):
... if not dirs:
... lowest_dirs.append(os.path.split(root)[-1])
>>> print(lowest_dirs)
['son_dir1', 'grandson_dir1']