Skip to content

Instantly share code, notes, and snippets.

@wamsachel
Created November 19, 2015 00:44
Show Gist options
  • Select an option

  • Save wamsachel/bd78d1cbfa727f590050 to your computer and use it in GitHub Desktop.

Select an option

Save wamsachel/bd78d1cbfa727f590050 to your computer and use it in GitHub Desktop.
I wanted a simple way to recursively move through directory tree and remove filenames containing a certain string
#!/usr/bin/env python
import argparse
import os
# Handle command line args
try:
arg_parser = argparse.ArgumentParser(description = 'Will recursively traverse a directory tree,\
and remove all files and directories that match any passed in regular expressions')
arg_parser.add_argument('dir', help = 'dir to start tree traversal process')
arg_parser.add_argument('search_str', help = 'search_str to compare against filenames to \
determine if they get removed')
# arg_parser.add_argument('-o', '--optional_arg', choices = ['opt1', 'opt2'], required = False)
arg_parser.add_argument('-v', '--verbose', help='increase output verbosity', action='store_true')
args = arg_parser.parse_args()
except Exception as e:
print e
raise Exception('[!] Error when parsing command line arguments')
starting_dir = args.dir
search_str = args.search_str
verbose = args.verbose
if os.path.isdir(starting_dir):
dir_walker = os.walk(starting_dir)
for a_walk in dir_walker:
dir_files = a_walk[2]
for filename in dir_files:
if search_str in filename:
try:
filepath = os.path.join(a_walk[0], filename)
os.remove(filepath)
if verbose is True:
print '[*] Removing\t{}'.format(filename)
except Exception as e:
print e
print '[!] Error occured when removing {}'.format(filename)
else:
raise Exception('[!] Expected {} to be a directory'.format(starting_dir))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment