Solved

Identify Directories with No Subdirectories and Take Action

Posted on 2011-03-11
8
419 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
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

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
ID: 35112975
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
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
treat_leafdir_files(mydir)

Open in new window

0
 
LVL 15

Assisted Solution

by:mish33
mish33 earned 100 total points
ID: 35116682
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 16

Expert Comment

by:gelonida
ID: 35118191
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
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.
0
 

Author Comment

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

Author Closing Comment

by:Ithizar
ID: 36444894
Thanks, everyone!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
None is returned 6 40
python - Creating a function to stop repetition of code 2 312
looping 11 34
Downgrading from Python 3.4.5 to 3.4.3 5 15
Plenty of writing has gone on the web trying to compare Python with other competitive programming languages and vice versa. However, not much has been put into a wholistic perspective. This article should help you decide whether to adopt Python as a…
Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
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 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…

930 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

19 Experts available now in Live!

Get 1:1 Help Now