Identify Directories with No Subdirectories and Take Action

Posted on 2011-03-11
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 17

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 17

Expert Comment

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

Accepted Solution

gelonida earned 1600 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

LVL 15

Assisted Solution

mish33 earned 400 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 17

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

Enroll in September's Course of the Month

This month’s featured course covers 16 hours of training in installation, management, and deployment of VMware vSphere virtualization environments. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

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

The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

719 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