Last active
May 21, 2020 18:43
-
-
Save ksaylor11/5a399c95c30d064f9caac3b7871c4a50 to your computer and use it in GitHub Desktop.
python script to clean up folder
This file contains 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
import argparse | |
import os.path | |
import sys | |
import time | |
import traceback | |
# setup argument parser | |
# allows for use in more than one environment | |
parser = argparse.ArgumentParser(description='clean out Unimarket files and logs') | |
parser.add_argument('dir', metavar='dir', help='absolute file path of Unimarket application') | |
parser.add_argument('--age', help='age of files to be cleaned up in seconds. default is one year: 31557600', type=int, default=31557600) | |
parser.add_argument("--audit", help="run script in audit mode", action='store_true') | |
parser.add_argument("-v", "--verbosity", help="level of program output", action='store_true') | |
args = parser.parse_args() | |
# known directories that need to be cleaned up | |
# gives a place to set know directories | |
dirs = [] | |
if args.dir: | |
dirs.append(args.dir) | |
if len(dirs) == 0: | |
sys.exit('no directories to cleanup') | |
# timestamp to beat is today + 1 year | |
# timestamp = time.time() - 31557600 | |
timestamp = time.time() - args.age | |
if args.audit: | |
print("running in audit mode") | |
else: | |
print("running production mode") | |
# count files | |
file_count = 0 | |
# test if directory exists | |
if os.path.isdir(args.dir): | |
for d in dirs: | |
folder_path = os.path.join(args.dir, d) | |
for root, folder, files in os.walk(folder_path): | |
for f in files: | |
file_path = os.path.join(root, f) | |
ctime = os.path.getctime(file_path) | |
if ctime < timestamp: | |
try: | |
if args.verbosity: | |
print("removing file: {0}".format(file_path)) | |
if not args.audit: | |
os.remove(file_path) | |
file_count += 1 | |
except OSError as e: | |
print('Error') | |
print(traceback.format_exc()) | |
# exit with summary | |
if args.audit: | |
print("total number of files to be removed: {0}".format(file_count)) | |
else: | |
print("total number of files removed: {0}".format(file_count)) | |
else: | |
sys.exit('directory does not exist') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
edited to use traceback and be more compatible with python 3