Last active
December 22, 2015 19:39
-
-
Save guildenstern70/6521117 to your computer and use it in GitHub Desktop.
Deletes all (sub)directories whose name contains a given string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
DirDeleter.py v0.2 | |
by Alessio Saltarin | |
Usage: python dirdeleter.py [initial_directory] [string] | |
Walks over all sub-directories starting from | |
[initial_directory] and deletes every directory that has | |
its name equal to [string] or containing [string] | |
""" | |
import os, sys, string | |
from stat import * | |
def walktree(dir, initdir): | |
for f in os.listdir(dir): | |
pathname = '%s\%s' % (dir, f) | |
mode = os.stat(pathname)[ST_MODE] | |
if S_ISDIR(mode): | |
walktree(pathname, initdir) | |
deletedir(pathname, initdir) | |
elif S_ISREG(mode): | |
pass | |
else: | |
print 'Attention: unknown %s' % pathname | |
def deletedir(nome, init): | |
if (string.rfind(nome,init)>0): | |
prunefiles(nome) | |
os.rmdir(nome) | |
print 'deleted: %s' % nome | |
else: | |
print 'visited: %s' % nome | |
def prunefiles(nome): | |
for f in os.listdir(nome): | |
path = '%s\%s' % (nome,f) | |
os.remove(path) | |
print ' --- deleted '+path | |
def printusage(): | |
print """ | |
Usage: python dirdeleter.py initial_dir string | |
where | |
initial_dir: | |
Initial directory to search for subdirectories to delete. | |
string: | |
The subdirectory containing 'string' in its name, or with a | |
name equals to 'string' will be deleted. | |
""" | |
if __name__ == '__main__': | |
if (len(sys.argv) == 3): | |
walktree(sys.argv[1], sys.argv[2]) | |
else: | |
printusage() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment