Skip to content

Instantly share code, notes, and snippets.

@wrunk
Created December 22, 2011 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrunk/1508586 to your computer and use it in GitHub Desktop.
Save wrunk/1508586 to your computer and use it in GitHub Desktop.
Python clean files from a directory
'''
Pass a time in seconds, and a base directory.
I will nuke anything older than now - seconds in that directory. Optionally
recursively
'''
from datetime import datetime
import os
from optparse import OptionParser
import time
TEST_RUN=True
def clean(base_path, seconds_old, recursive=False):
for current_path, dir_names, file_names in os.walk(base_path):
# lets not hit the clock for EACH file.. just each dir :)
now = time.time()
for name in file_names:
path = os.path.join(current_path, name)
mtime = os.path.getmtime(path)
dt = datetime.fromtimestamp(mtime)
if mtime < now - seconds_old:
if TEST_RUN:
print "Would have deleted file (%s) at with last mod time (%s)" % \
(path, dt)
else:
print "Deleting file (%s) at with last mod time (%s)" % \
(path, dt)
os.remove(path)
else:
print "Skipped file (%s) mtime (%s)" % (
path, dt
)
if recursive:
for dir in dir_names:
clean(os.path.join(current_path, dir), seconds_old, True)
if __name__ == "__main__":
parser = OptionParser()
parser.add_option(
"-b", "--base-path", dest="base_path", help="base directory to clean from")
parser.add_option(
"-s", "--seconds-old", dest="seconds_old",
help="seconds old to delete from")
parser.add_option(
"-r", "--recursive", dest="recursive", default=False,
help="seconds old to delete from")
(options, args) = parser.parse_args()
clean(options.base_path, int(options.seconds_old), options.recursive)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment