Commits

Randle Taylor committed 03911cd

crawl directory and check modified date

Comments (0)

Files changed (2)

+# Clean By Date #
+
+Just a simple script to walk a directory structure and delete files older
+than a given date.
+
+
+import argparse
+import datetime
+import os
+import time
+
+#----------------------------------------------------------------------
+def days_validator(days):
+    try:
+        days =  int(days)
+        if days < 0:
+            raise ValueError
+    except ValueError:
+        raise argparse.ArgumentTypeError("days must be an integer >= 0")
+
+    return days
+
+#----------------------------------------------------------------------
+def dir_validator(path):
+    path = os.path.abspath(path)
+    if not (os.path.exists(path) and os.path.isdir(path)):
+        raise argparse.ArgumentTypeError("%s does not exist or is not a directory" % path)
+    return path
+
+#----------------------------------------------------------------------
+def clean_dir(path,days):
+    """recursively walk path and delete files that have not been modified in
+    less than input # of days"""
+
+    threshold = datetime.date.today()-datetime.timedelta(days=days)
+
+    for directory, subdirs, files in os.walk(path):
+        for f in files:
+            fpath = os.path.join(directory,f)
+            modified = datetime.date.fromtimestamp(os.path.getmtime(fpath))
+
+            if modified < threshold:
+                print "delete this file:", fpath, modified
+
+
+
+
+
+if __name__  == "__main__":
+
+    parser = argparse.ArgumentParser(description='Walk a directory structure and delete files older (haven''t been modified) than input number of days')
+
+    parser.add_argument('directory', help='top level directory to walk through', type=dir_validator)
+    parser.add_argument('days', help='Delete files older (not modified) than this number of days',type=days_validator)
+
+    args = parser.parse_args()
+
+    clean_dir(args.directory,args.days)