Identify Directories with No Subdirectories and Take Action

Posted on 2011-03-11
Last Modified: 2012-05-11
Hi folks!

Trying to accomplish something in Python and looking for suggestions on the best way to make it happen.

I have a variable set that is the root of a series of directories (i.e. 'c:\folder'). In that directory is a series of other directories (i.e. 'c:\folder\subfolder'). Some of them contain files, some contain more subdirectories. None of them contain both.

I need Python to iterate down through the entire directory tree finding each directory in the tree that has NO subdirectories under it. In those directories, and only those directories, I need it to take a specific action on all the files in the directory.

So, it if checked c:\folder\subfolder and found only files, it would do x. If it found that c:\folder\subfolder\subsubfolder exists, it wouldn't do anything except move on down the tree.

Thoughts on the best way to achieve this?

Question by:Ithizar
LVL 16

Expert Comment

ID: 35112970
Attached script oses os.walk to traverse all directories.

If the list cotnaining all subdirectories is emptym then it is a directory, that you are looking for.
#!/usr/bin/env python

import os
import sys


leafdirs = []
for dirpath, dirnames, filenames in os.walk('.'):
    if len(dirnames) == 0:

print "leafdirs",leafdirs

Open in new window

LVL 16

Expert Comment

ID: 35112975
The documentation can be found at 
Just search for walk
LVL 16

Accepted Solution

gelonida earned 400 total points
ID: 35113009
I wasn't reading the entire post. Apologies:

Below a script doing something with all files in directories, that do not have a subdirectory
import os
import sys

def treat_leafdir_files(topdir):
    for dirpath, dirnames, filenames in os.walk(topdir):
        if len(dirnames) == 0:
            for filename in filenames:
                fullpath = os.path.join(dirpath, filename)
                print "do something with", fullpath

mydir = sys.argv[1] # for testing from the command line

Open in new window

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

LVL 15

Assisted Solution

mish33 earned 100 total points
ID: 35116682

line 6 better rephrase as
   if not dirnames:

and protect 11,12 to be executed only when run from command line (and not when this module is imported):

if __name__ == "__main__":
  # lines 11,12
LVL 16

Expert Comment

ID: 35118191
Hi Mish,

 if not dirnames
is more pythonic

if len(dirnames) == 0
on the other hand is easier to understand for people who aren't  that used to  Python

I agree also
if __name__ == "__main__":
should be used in any real script.

In answers to EE however I try to not write too much boilerplate code an left it thus off.

My own scripts do also always start with

#!/usr/bin/env python
, which is also intentionally left off.

Thanks for your comment though.
It will make clearer, that my answer is not an entire, clean python script,
but just a working example explaining how one could solve the problem asked.

LVL 29

Expert Comment

ID: 35121283
I second to gelonida's opinion
if len(dirnames) == 0:

on the other hand is easier to understand for people who aren't  that used to  Python

We could debate about "if not dirnames:"... whether it is more pythonic or not.  It could be viewed as "pythonic" because Python defines the behaviour of a list in a boolean context.  On the other hand, it may be confusing for some people.  The "len(dirnames)" is self-explanatory.

Actually, relying on a boolean context behaviour is a kind of more implicit.  And even the interpreter of Python suggests...

>>> import this
The Zen of Python, by Tim Peters
Explicit is better than implicit.
Readability counts.

Author Comment

ID: 35224400
Just letting everyone know that I have not abandoned this question, just that other things have gotten in the way of my continuing this project. As soon as I get back to it, I will report back.

Author Closing Comment

ID: 36444894
Thanks, everyone!

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Here I am using Python IDLE(GUI) to write a simple program and save it, so that we can just execute it in future. Because when we write any program and exit from Python then program that we have written will be lost. So for not losing our program we…
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

680 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question