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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With