Dear keenr1214,
The script follows. As before, there are constants to set at the
beginning, and there's an optional log file that can get fairly big
over time.
I'm anxious to meet all your needs and to win a five-star rating for
every answer I provide, so please let me know if you have any trouble
with the script or if there are additional details or program features
I should provide. I'm not satisfied until you're satisfied. For this
reason, I ask that you refrain from rating my answer until I've had a
chance to address all of your concerns.
leapinglizard
# begin sweeper.py
# This program identifies directories whose names are in the date
# format mm-dd-yy, and deletes them if they are older than a certain
# number of days.
# *** adjust constants as necessary ***
BASE_DIRECTORY = 'archive' # search in this directory for old archives
MAXIMUM_DAYS_ALLOWED = 31 # delete archive folders older than this
LOG_FILE = 'sweeper_log.txt' # record actions here; set to '' for no log
# *** end of constants ***
import sys, os, string, re
import time
import calendar
def msg(s):
if LOG_FILE.strip() != '':
open(LOG_FILE, 'a').write(s+'\n')
print s
msg('[%s] starting sweeper.py' % time.asctime())
(cy, cm, cd) = time.localtime()[:3]
mm = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]
def calspan((y0, m0, d0), (y1, m1, d1)):
if y0 > y1:
return -1
if y0 == y1 and m0 > m1:
return -1
if (y0 == y1 and m0 == m1) and d0 > d1:
return -1
ct = 0
while (y0 < y1 or m0 < m1) or d0 < d1:
ct += 1
d0 += 1
if d0 <= mm[calendar.isleap(y0)][m0-1]:
continue
d0 = 1
m0 += 1
if m0 <= 12:
continue
m0 = 1
y0 += 1
return ct
for name in os.listdir(BASE_DIRECTORY):
match = re.search('^(\d\d)-(\d\d)-(\d\d)$', name)
if not match:
continue
fm = int(match.group(1))
fd = int(match.group(2))
fy = 2000+int(match.group(3))
span = calspan((fy, fm, fd), (cy, cm, cd))
if span <= MAXIMUM_DAYS_ALLOWED:
if span < 0:
msg('skipping "%s", which has a date in the future' % name)
else:
msg('skipping "%s", which is %d days old' % (name, span))
continue
msg('deleting "%s", which is %d days old' % (name, span))
fname = '%s/%s' % (BASE_DIRECTORY, name)
if os.path.isdir(fname):
os.removedirs(fname)
else:
os.remove(fname)
msg('[%s] ending sweeper.py\n' % time.asctime())
# end sweeper.py |