Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing final (leaf?) nodes in directory listing Python

Tags:

python

os.walk

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
like image 739
Dee Avatar asked Aug 30 '25 16:08

Dee


1 Answers

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)

like image 147
Dan D. Avatar answered Sep 02 '25 06:09

Dan D.