Created
April 18, 2017 22:20
-
-
Save paceaux/ad164f9954d910bca7e3c39211317930 to your computer and use it in GitHub Desktop.
Cleaner: get rid of old files in a directory
This file contains hidden or 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
# Shamelessly stolen from https://www.quora.com/As-a-programmer-what-tasks-have-you-automated-to-make-your-everyday-life-easier/answer/Cory-Engdahl?srid=tVE5 | |
# | |
# Usage: | |
# python cleaner.py -f [full/path/to/folder] | |
# arguments | |
# -p, --path : fully qualified path to folder (required) | |
# -d, --days : Age in days of the file to delete (optional, default is 1 day) | |
# -e, --exclude: name of files to save (optional) | |
# -i, --include: name of files to delete regardless of timeframe (optional) | |
import sys,getopt | |
import os | |
import time | |
import shutil | |
import logging | |
def main(argv): | |
delete_always = [] | |
delete_never = [] | |
delete_after_days = 1 | |
delete_after = delete_after_days * 24 | |
delete_path= '/Users/username/Downloads/' | |
try: | |
opts, args = getopt.getopt(argv, "p:d:e:i:", ["path=", "days=", "exclude=", "include="]) | |
except getopt.GetoptError: | |
print "error with directory" | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt in ("-p", "--path"): | |
delete_path= arg | |
elif opt in ("-d", "--days"): | |
delete_after_days = arg | |
elif opt in ("-e", "--exclude"): | |
delete_never = arg | |
elif opt in ("-i", "--include"): | |
delete_always = arg | |
logging.basicConfig(format='%(asctime)s %(message)s', filename=delete_path+'cleanup.log', level=logging.INFO) | |
def rotten_file(file): | |
name, ext = os.path.splitext(file) | |
return (time.time() - os.path.getmtime(delete_path + | |
file) > (delete_after*3600)) | |
def precious_file(file): | |
name, ext = os.path.splitext(file) | |
return ext in delete_never | |
def worthless_file(file): | |
name, ext = os.path.splitext(file) | |
return ext in delete_always | |
# files to evaluate | |
contents = [] | |
# omit hidden files | |
for file in os.listdir(delete_path): | |
if not file.startswith('.'): | |
contents.append(file) | |
# begin log | |
logging.info('Cleaning Directory') | |
# evaluate all files | |
for file in contents: | |
fullpath = delete_path + file | |
if (not rotten_file(file) and not worthless_file(file)): | |
continue | |
elif not precious_file(file): | |
if os.path.isfile(fullpath): | |
os.remove(fullpath) | |
logging.info('deleting file %s', file) | |
elif os.path.isdir(fullpath): | |
shutil.rmtree(fullpath) | |
logging.info('deleting directory %s', file) | |
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