4

I can walk the directory and print just folder/directory names but I would like to exclude folder names of directories that contain other directories. For some reason I am calling that a "final node" in the tree structure but I could well be fooling myself, wouldn't be the first time. =) On reveiewing the list of other answers perhaps this is called a "leaf node" ?

    import os
    chosen_path = (os.getcwd())
    FoldersFound =[] 
    for root, dirs, files in os.walk(chosen_path, topdown=True):
        for name in dirs:
            FoldersFound.append(name)
    FoldersFound.sort()
    for FolderName in FoldersFound:
        print FolderName
Dee
  • 191
  • 1
  • 11

2 Answers2

8

This will print the full names of the directories that have no child directories:

for root, dirs, files in os.walk(here):
    if not dirs:
        print '%s is a leaf' % root

To print only the base name, replace root with os.path.basename(root)

To put them in a list use:

folders = []
for root, dirs, files in os.walk(here):
    if not dirs:
        folders.append(root)

Likewise to put only the basename in the list, replace root with os.path.basename(root)

Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • Or the equivalent one-liner (it is Python, after all): `[root for root, dirs, files in os.walk(here) if not dirs]` :) – Hannes Ovrén Jan 26 '15 at 09:02
  • thanks gents, I thought I tried to use `if not dirs` but I must have botched the syntax...again no surprise. I'll try again. – Dee Jan 26 '15 at 09:05
  • @HannesOvrén Your solution works except that it gives me the full path when I am only wanting to print/collate the final foldername. Possible with your solution? – Dee Jan 26 '15 at 09:09
  • 2
    Use `os.path.basename(root)` rather than `root`. – Dan D. Jan 26 '15 at 09:17
  • @DanD. thanks, got my result. If I can I'll even see if I can shoehorn that into Hannes' one liner =) Many thanks to you all. – Dee Jan 26 '15 at 09:29
  • Showhorning it really just comes down to `[os.path.basename(root) for root, dirs, files in os.walk(here) if not dirs]` as Dan D sugested. – Hannes Ovrén Jan 26 '15 at 09:42
  • Thanks @HannesOvrén It seems a couple of directories are _failing to be picked up_ in this. I've done it multiple times, checked the directories for strange permissions (anything that might make one directory different from another) but I cannot see anything... – Dee Jan 26 '15 at 10:26
0

This is a solution using "os.listdir":

import os


def print_leaf_dir(pathname, dirname):
dirnames = [subfolder for subfolder in os.listdir(os.path.join(pathname, dirname)) if os.path.isdir(os.path.join(pathname, dirname, subfolder))]

if(dirnames):
    for subfolder in dirnames:
        print_leaf_dir(os.path.join(pathname, dirname), subfolder)
else:
    print(os.path.join(pathname, dirname))


if(__name__ == '__main__'):
    print_leaf_dir(r'C:\TEMP', '')
wagnerpeer
  • 937
  • 7
  • 22