9
import os

for dirpaths, dirnames, filenames in os.walk(mydir):
    print dirpaths

gives me all (sub)directories in mydir. How do I get only the directories at the very bottom of the tree?

12
  • 1
    Recursively go all the way down and don't come back? Commented Jul 30, 2013 at 19:32
  • 1
    "very bottom" may not be meaningful depending on how you have your directories structured. Commented Jul 30, 2013 at 19:36
  • 1
    Have you tried anything? Commented Jul 30, 2013 at 19:37
  • 1
    Can you show and example of a directory tree and the output you would like to achieve? Commented Jul 30, 2013 at 19:37
  • By 'very bottom' do you mean the end of each path tree? Commented Jul 30, 2013 at 19:39

4 Answers 4

18

This will print out only those directories that have no subdirectories within them

for dirpath, dirnames, filenames in os.walk(mydir):
    if not dirnames:
        print dirpath, "has 0 subdirectories and", len(filenames), "files"
Sign up to request clarification or add additional context in comments.

Comments

4

Like this?

for dirpaths, dirnames, filenames in os.walk(mydir):
    if not dirnames: print dirpaths

Comments

2

I saw two solutions for showing leaf directories (i.e. those that does not contain sub-dir). Bottom-most directories, on the other hand, are not only leaf directories, but also are at the maximum depth. Here is a crude way to figure out the bottom-most directories:

import os

mydir = '/Users/haiv/src/python'
max_depth = 0
bottom_most_dirs = []
for dirpath, dirnames, filenames in os.walk(mydir):
    depth = len(dirpath.split(os.sep))
    if max_depth < depth:
        max_depth = depth
        bottom_most_dirs = [dirpath]
    elif max_depth == depth:
        bottom_most_dirs.append(dirpath)
print bottom_most_dirs

Comments

1
import os

mydir='/home/'
print [dirpaths for dirpaths, dirnames, filenames in os.walk(mydir) if not dirnames]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.