Last active
August 29, 2015 14:08
-
-
Save h2rashee/7440877e590908baef5a to your computer and use it in GitHub Desktop.
Removes old files from a directory
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
# Question | |
# | |
# We have many applications running that store temporary files in /var/tmp, which fills up over time. | |
# | |
# Write a function that cleans out files older than a user specified number of days and | |
# removes empty directories recursively. | |
# | |
import os | |
import sys | |
import datetime | |
def isFileOld(fileItem, daysOld): | |
cutoff = datetime.datetime.today() - datetime.timedelta(days=daysOld) | |
fileModDateTime = datetime.datetime.fromtimestamp(os.path.getmtime(fileItem)) | |
return fileModDateTime < cutoff | |
def cleanup(directory, daysOld): | |
for item in os.listdir(directory): | |
# Absolute file path in case this script is run from elsewhere | |
# and for recursive calls | |
absItem = os.path.join(directory, item) | |
# Folder case | |
if os.path.isdir(absItem): | |
# Non-empty folder | |
if os.listdir(absItem): | |
cleanup(absItem, daysOld) | |
# Empty folder | |
if not os.listdir(absItem): | |
print "Removing folder " + absItem | |
os.rmdir(absItem) | |
# File and old case | |
if os.path.isfile(absItem) and isFileOld(absItem, daysOld): | |
os.remove(absItem) | |
print "Deleting " + absItem | |
folder = "/var/tmp" | |
days = sys.argv[1] | |
cleanup(folder, int(days)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment