#!/usr/bin/env python import os import shutil import sys from datetime import datetime, date import argparse folders = [] periods = [ { "min": 0, "max": 3, "amount": 4, "count": 0, }, { "min": 4, "max": 6, "amount": 1, "count": 0, }, { "min": 7, "max": 13, "amount": 1, "count": 0, }, { "min": 14, "max": 20, "amount": 1, "count": 0, }, { "min": 21, "max": 27, "amount": 1, "count": 0, }, { "min": 28, "max": 55, "amount": 1, "count": 0, }, { "min": 56, "max": 83, "amount": 1, "count": 0, }, { "min": 84, "max": 111, "amount": 1, "count": 0, }, { "min": 112, "max": 1111, "amount": 0, "count": 0, }, ] parser = argparse.ArgumentParser(description='Remove folders to keep three daily, for weekly and three monthly') parser.add_argument('datadir', help='directory, where placed YYYY-MM-DD folders') parser.add_argument('--today', help='set YYYY-MM-DD as current date') parser.add_argument('--dry-run', action='store_true') args = parser.parse_args() #print args customToday = '' if args.today: customToday = args.today if customToday != '': dateToday = datetime.strptime(customToday, "%Y-%m-%d").date() else: dateToday = date.today() datadir = args.datadir print 'TODAY IS', dateToday print 'Processing ', datadir for file in os.listdir(datadir): realpath = os.path.join(datadir, file) if os.path.isdir(realpath): try: date_object = datetime.strptime(file, "%Y-%m-%d") except: date_object = False if date_object: age = int((dateToday - date_object.date()).days) item = { "file": file, "realpath": realpath, "date": date_object.date(), "age": age } folders.append(item) folders = sorted(folders, reverse=True) foldersUntouched = "" for folder in folders: if folder['age'] < 0: continue remove = "" for p in periods: if folder['age'] >= p["min"] and folder['age'] <= p["max"]: print folder['file'], folder['age'], p["min"], p["max"], p["amount"] if p["count"] < p["amount"]: p["count"] += 1 else: remove = "REMOVE" info = " {} [{} - {}] {} | {}".format(folder['age'], p["min"], p["max"], p["amount"], remove) print info if remove != '': if not args.dry_run: #os.rmdir(folder["realpath"]) # shutil.rmtree(folder["realpath"]) shutil.move(folder["realpath"], folder["realpath"] + " deleted") else: remove += " dry-run" remove += " DONE " + info else: foldersUntouched += folder['file'] + info + "\n" print folder['file'], info, remove print "-----" print foldersUntouched