Remove all directories using wildcard

Tim Golden mail at timgolden.me.uk
Fri Mar 18 12:55:18 EDT 2011


On 18/03/2011 16:41, JSkinn3 wrote:
> I'm new to python and I am trying to figure out how to remove all sub
> directories from a parent directory using a wildcard.  For example,
> remove all sub directory folders that contain the word "PEMA" from the
> parent directory "C:\Data".
>
> I've trying to use os.walk with glob, but I'm not sure if this is the
> right path to take.

You've got a few options. And it depends whether you just want
to get it done as simply as possible or whether you're using
this as a learning exercise.

Assuming it's somewhere between the two then you're on the right
track with os.walk:

<code - untested>
import os
import shutil

for dirpath, dirnames, filenames in os.walk ("c:/data"):
   for dirname in dirnames:
     if "pema" in dirname.lower ():
       pema_path = os.path.join (dirpath, dirname)
       print "Removing", pema_path
       shutil.rmtree (pema_path)
       dirnames.remove (dirname)

</code>

The key is that os.walk is designed so that the dirnames
list can be mutated in place to remove directories which
are to be ignored for whatever reason. In this case, you
delete the directory tree and remove it from os.walk's
attention.

BTW the use of os.walk here is only necessary if you need to
remove "*pema*" directories at any level under c:\data. If
you only need those immediately under c:\data then you can
just use glob.glob in union with shutil.rmtree

TJG



More information about the Python-list mailing list