سؤال

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!

هل كانت مفيدة؟

المحلول

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']

نصائح أخرى

Use os.walk and a list comprehension:

[os.path.split(r)[-1] for r, d, f in os.walk(tree) if not d]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top