Solved

Python - Script to find if subfolder exists or not

Posted on 2009-05-13
2
1,147 Views
Last Modified: 2012-08-13
I'm new to python.

I need to run a script which will delete files/directorys within a subfolder structure only if certain directorys exist.

Parent directory (p:\*fund*\) could be any directory name, for example:
p:\abc\letters\reject\
p:\def\letters\printed\
p:\ghi\letters\

So in above scenario, need to search the root directory (p:\*.*\letters\) for directorys called either reject or printed, then if exist delete the file contents of reject or printed.

I have many task like this one to do, hope that someone can provide me one example then I can tinker with it from then on.

Any help would be apprciated!!

Thanks in advance.
0
Comment
Question by:Rich55555
2 Comments
 
LVL 3

Expert Comment

by:ilalopoulos
ID: 24381019
Running the python code at the end of this post you will delete all subfolders that their root have names included in DIRS_TO_DEL and are under ROOT_DIR as you asked.

Remove the # in last line from #shutil.rmtree(td) to actually delete the subfolders (else it only prints them to the console)


TEST:

Beggining with a dir structure like this (plus some files):

Directory of C:\area51
New Text Document (2).txt
New Text Document (3).txt
New Text Document.txt

Directory of C:\area51\printed
New Text Document (2).txt
New Text Document.txt

Directory of C:\area51\printed\a
New Text Document.txt

Directory of C:\area51\printed\b

Directory of C:\area51\printed\c

Directory of C:\area51\printed\reject

Directory of C:\area51\test

Directory of C:\area51\test\a

Directory of C:\area51\test\a\reject

Directory of C:\area51\test\b

Directory of C:\area51\test\printed

Directory of C:\area51\test\reject

Directory of C:\area51\test\reject\a


and The end result is this:

Directory of C:\area51

New Text Document (2).txt
New Text Document (3).txt
New Text Document.txt

Directory of C:\area51\test

Directory of C:\area51\test\a

Directory of C:\area51\test\b
#reject.py

import os

import shutil
 

ROOT_DIR = 'c:\\area51'

DIRS_TO_DEL = ['printed', 'reject']
 

todel=[]
 

for p,d,f in os.walk(ROOT_DIR):

    for dtd in DIRS_TO_DEL:

        try:

            d.remove(dtd)

            todel.append(os.path.join(p,dtd))

        except:

            pass
 

for td in todel:

    print td

    #shutil.rmtree(td)

Open in new window

0
 
LVL 28

Accepted Solution

by:
pepr earned 500 total points
ID: 24382618
In my opinion, it is better to do the second loop through the found-subdirectories list (they exist) and only then to check then against the list of directories that should be deleted. The above solution also does not solve the first part of the question.

See the snippet below. Make a test directory, copy the attached makeTestDirs.py to it and save the snippet as a.py. Then run the makeTestDirs.py and then a.py twice. You can observe the following in the cmd window:

======================================================
c:\tmp\___python\Rich55555>makeTestDirs.py

c:\tmp\___python\Rich55555>a.py

from A\B1
remove A\B1\letters

from A\B2
remove A\B2\letters

from A\C3
remove A\C3\gossips
remove A\C3\letters

from A\letters

c:\tmp\___python\Rich55555>a.py

from A\B1

from A\B2

from A\C3

from A\letters

c:\tmp\___python\Rich55555>

======================================================

You can see that there is nothing to remove after the first run.

import glob

import os

import shutil
 
 

# The following generator is a part of the solution.

# It takes one root directory (the first argument, 

# could be relative), and returns the wanted

# subdirectories (the other arguments) joined with the root.

#

def myWalker(root, *subdirs):

    for dirpath, dirnames, filenames in os.walk(root):

        for d in dirnames:

            if d in subdirs:

                yield os.path.join(dirpath, d)
 
 

if __name__ == '__main__':

   

    # Get the list of roots and pass each of them to the generator

    # if they are directories. Here the glob module is probably

    # the easies to form such list.

    #

    for root in glob.glob('A/*'):

        if os.path.isdir(root):

            print '\nfrom', root

            for directory in myWalker(root, 'letters', 'gossips'):

                print 'remove', directory

    

        

    # Use the same approach for removing the real removing the directories.

    for root in glob.glob('A/*'):

        if os.path.isdir(root):

            for directory in myWalker(root, 'letters', 'gossips'):

                shutil.rmtree(directory)

     

Open in new window

makeTestDirs.py.txt
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

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…
Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
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…

747 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

17 Experts available now in Live!

Get 1:1 Help Now