Last active
October 25, 2016 15:43
-
-
Save JohnPreston/f0925e70b10e655be3b0b2590e837690 to your computer and use it in GitHub Desktop.
Very simple script to remove all files in a folder based on expiration timestamp
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
| #!/usr/bin/env python | |
| """ | |
| Script to remove all folders in the given path that are older than 24H | |
| """ | |
| import os | |
| import sys | |
| import argparse | |
| import datetime | |
| _basedir = os.path.abspath(os.path.dirname(__file__)) | |
| def parser(): | |
| parser = argparse.ArgumentParser(description='Script to delete all files in the specified path that match regexp timestamp') | |
| parser.add_argument("--path", required=True) | |
| args = parser.parse_args() | |
| return args | |
| def remove_recurse(path): | |
| """ | |
| Function to recursively remove all files and directories in the given path | |
| :param path: path of the directory to remove | |
| """ | |
| dir_list = os.listdir(path) | |
| for item in dir_list: | |
| if os.path.isdir(item): | |
| remove_recurse(item) | |
| elif os.path.isfile(item): | |
| os.remove(item) | |
| def delete_old(): | |
| """ | |
| Function to delete all old files / folders in the given path | |
| """ | |
| args = parser() | |
| path = os.path.abspath(args.path) | |
| print "ROOT PATH : %s" % path | |
| now = datetime.datetime.utcnow() | |
| dir_list = os.listdir(path) | |
| for directory in dir_list: | |
| if os.path.isdir(os.path.join(path, directory)): | |
| timestamp = datetime.datetime.strptime(directory, "%Y-%m-%d-%H-%M-UTC") | |
| if directory.endswith('00-UTC'): | |
| print "This is a top of hour backup - MAX AGE is 1 day" | |
| if now - timestamp > datetime.timedelta(days=1): | |
| print "%s is older than 1 day - REMOVING" % directory | |
| try: | |
| os.chdir(os.path.join(path, directory)) | |
| remove_recurse(os.path.join(path, directory)) | |
| os.rmdir(os.path.join(path, directory)) | |
| os.chdir(_basedir) | |
| except: | |
| print "Failed to remove %s" % directory | |
| else: | |
| print "%s is younger than 1 day - KEEPING" % directory | |
| else: | |
| print "This is a 15min interval backup - MAX AGE is 12h" | |
| if now - timestamp > datetime.timedelta(hours=12): | |
| print "%s is older than 12 hours - REMOVING" % directory | |
| os.chdir(os.path.join(path, directory)) | |
| remove_recurse(os.path.join(path, directory)) | |
| os.rmdir(os.path.join(path, directory)) | |
| os.chdir(_basedir) | |
| else: | |
| print "%s is young - KEEPING" % directory | |
| if __name__ == '__main__': | |
| delete_old() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment