Get a list of the lowest subdirectories in a tree
Asked Answered
H

2

9

I have a path to a certain directory, and I need to get a list of all of it's sub-directories that themselves don't contain any sub-directories.

For example, if I've got the following tree:

-father_dir:
    -son_dir1:
        -grandson.txt
    -son_dir2:
        -grandson_dir1:
            -greatgrandson1.txt

I'd like to have a list containing: [son_dir1, grandson_dir1]

What I tried: I used os.walk() to get all of the sub-directories in father_dir, and now I'm trying to iterate over each sub-directory's contents (with os.listdir()) and find if it contains directories... so far I wasn't successful (as os.listdir() doesn't give the path to the directory but rather only its name), besides it seems to be a very cumbersome method.

Any simple solution would be welcome. Thanks!

Hypercatalectic answered 7/4, 2014 at 17:49 Comment(0)
T
16
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']
Tunicate answered 7/4, 2014 at 17:51 Comment(1)
Beautiful (both the implementation and the explanation)! Thank you so much! :-)Hypercatalectic
B
4

Use os.walk and a list comprehension:

[os.path.split(r)[-1] for r, d, f in os.walk(tree) if not d]
Bensen answered 7/4, 2014 at 18:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.