We all have them, those applications where they perform a backup periodically and place the backup inside the programs folder structure. this is great if you’re trying to recover from a problem within the application, but what about if the hard drive goes? and most of the time, the program just keeps dumping backups and doesn’t clean up old ones.

I wrote this script to handle these two problems. At the beginning of the code you can modify strsrc and srdst to be the source(strsrc) and destination(strdst) that you need for your application. You can also set the age variable to be the number of days you want to retain backups in each directory for.

As always, I don’t claim that my code is pretty, just that it works. feel free to modify or comment on it.

import shutil, os, stat, time
from datetime import date, timedelta

strsrc = "c:\\program files\\Application\\backup"
strdst = "S:\\bkup"
age = 14

strDeleteFromDate = date.today() - timedelta(days=age)

for files in os.walk(strsrc):
	for item in files[2]:
		strFileLoc = strsrc + "\\" + item
		strdateused = os.stat(strFileLoc).st_mtime
		year, day, month = time.localtime(strdateused)[:3]
		strLastUsed = date(year, day,month)
		if strLastUsed < strDeleteFromDate:
			print "/* ", item, ",", strLastUsed, ", Delete */"
			os.remove(strFileLoc)
		else:
			print "/* ", item, ",", strLastUsed, ", Keep */"
			shutil.copy2(strFileLoc, strdst)

for contents in os.walk(strdst):
	for things in contents[2]:
		strFileLoc = strsrc + "\\" + things
		strdateused = os.stat(strFileLoc).st_mtime
		year, day, month = time.localtime(strdateused)[:3]
		strLastUsed = date(year, day,month)
		if strLastUsed < strDeleteFromDate:
			print "/* ", item, ",", strLastUsed, ", Delete bkup */"
			os.remove(strFileLoc)
		else:
			print "/* ", item, ",", strLastUsed, ", Keep bkup */"

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2013 Suffusion theme by Sayontan Sinha