Skip to content

Instantly share code, notes, and snippets.

@raykendo
Last active August 16, 2017 17:00
Show Gist options
  • Save raykendo/d5dd27a1a7db458118dec9a4caf61e0c to your computer and use it in GitHub Desktop.
Save raykendo/d5dd27a1a7db458118dec9a4caf61e0c to your computer and use it in GitHub Desktop.
Removing junk files from a folder recursively (Python)
#!/usr/bin/env python
#
# delete-stuff2.py: delete specific files and folders within subdirectories of a folder.
# by raykendo
# Python 2.7+
#
import os
import stat
import sys
def usage():
print 'Usage for files: delete-stuff2.py DIRECTORY FILENAME'
print 'Usage for folders: delete-stuff2 DIRECTORY /FOLDERNAME'
sys.exit(1)
def main(argv):
if len(argv) < 2:
usage()
dir = os.path.abspath(argv[0])
print 'Reading file names'
removed = 0
for fileName in argv[1:]:
for root, dirs, files in os.walk(dir):
for name in files:
if name.upper() == fileName.upper():
path = os.path.join(root, name)
os.remove(path)
removed += 1
if fileName.startswith('/') or fileName.startswith('\\'):
for name in dirs:
if name.upper() == fileName[1:].upper():
path = os.path.join(root, name)
os.rmdir(path)
removed += 1
print 'Done, %d files removed.' % (removed)
if __name__ == '__main__':
main(sys.argv[1:])
#!/usr/bin/env python
#
# delete-stuff3.py: delete specific files and folders within subdirectories of a folder.
# by raykendo
# Python 3.x
#
import os
import stat
import sys
def usage():
print('Usage for files: delete-stuff3.py DIRECTORY filename')
print('Usage for folders: delete-stuff3 DIRECTORY /foldername')
sys.exit(1)
def main(argv):
if len(argv) < 2:
usage()
dir = os.path.abspath(argv[0])
print('Reading file names')
removed = 0
for fileName in argv[1:]:
for root, dirs, files in os.walk(dir):
for name in files:
if name.upper() == fileName.upper():
path = os.path.join(root, name)
os.remove(path)
removed += 1
if fileName.startswith('/') or fileName.startswith('\\'):
for name in dirs:
if name.upper() == fileName[1:].upper():
path = os.path.join(root, name)
os.rmdir(path)
removed += 1
print('Done, %d files removed.' % (removed))
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment