Saturday, June 30, 2012

A python clip to delete subdirectories

I wrote a short python program to delete all subdirectories with a particular name in a directory. I worte this in order to delete all the Debug directories that visual studio 2005 generated automatically for me when I was trying to back up the whole workspace on dropbox. It was a huge directory, after check all the files and subdirectories in the directory, I found out there are many useless craps that I don't have to back up together with the source files. So I wrote this code clip. But after I finished it, I  found out that by just search the subdirectorie with the name of which I want to delete, I can delete them all together. How stupid I am.  Any way, I put the code here in case someone may need it.
import shutil, os, re

NAME = "Debug"

matchpaths = []

current = os.walk(".")
for (path, dirs, files) in current:
#    print "path", path
#    print "dirs", dirs
#    print "files", files
#    print "----"

    for di in dirs:
        if di == NAME:
            matchpaths = matchpaths + [path + "\\" + di]

#print "mathpaths: ", matchpaths

#for path in matchpaths:
#    print path

for path in matchpaths:
    shutil.rmtree(path, True)
print len(matchpaths), "directories removed!"

No comments:

Post a Comment