Solved

Identify Directories with No Subdirectories and Take Action

Posted on 2011-03-11
8
414 Views
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?

Thanks,
Ithizar
0
Comment
Question by:Ithizar
8 Comments
 
LVL 16

Expert Comment

by:gelonida
Comment Utility
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

print 
os.chdir(sys.argv[1])

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

print "leafdirs",leafdirs

Open in new window

0
 
LVL 16

Expert Comment

by:gelonida
Comment Utility
The documentation can be found at
http://docs.python.org/library/os.html
Just search for walk
0
 
LVL 16

Accepted Solution

by:
gelonida earned 400 total points
Comment Utility
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
treat_leafdir_files(mydir)

Open in new window

0
 
LVL 15

Assisted Solution

by:mish33
mish33 earned 100 total points
Comment Utility
gelonida,

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
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 16

Expert Comment

by:gelonida
Comment Utility
Hi Mish,


Agreed:
 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.








0
 
LVL 28

Expert Comment

by:pepr
Comment Utility
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.
0
 

Author Comment

by:Ithizar
Comment Utility
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.
0
 

Author Closing Comment

by:Ithizar
Comment Utility
Thanks, everyone!
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
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 …

772 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now