Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Identify Directories with No Subdirectories and Take Action

Posted on 2011-03-11
8
Medium Priority
?
481 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 17

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 17

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 17

Accepted Solution

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

Open in new window

0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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.

 
LVL 15

Assisted Solution

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

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 29

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

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

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

Installing Python 2.7.3 version on Windows operating system For installing Python first we need to download Python's latest version from URL" www.python.org " You can also get information on Python scripting language from the above mentioned we…
Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
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 …
Suggested Courses

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