Wednesday, April 10, 2013

Temp File Cleanup with Python

In the short few months I've been using Python, I've been impressed by it's versitility, performance and small footprint. Here is a quick of example of how to used Python to loop through a directory and delete old files based on the last modified date.

On Windows:

import os, time, sys
from datetime import datetime

path = r"c:\tempFiles" # Target Directory
logfile = r"c:\log\tempFileCleanup.txt"  # Log File
days = 10  # Delete files older than X days

now = time.time()

for f in os.listdir(path):
 full = path + '\\'
 full = full + f
 #print(full)
 #print(os.stat(full).st_mtime)
 if os.stat(full).st_mtime < now - days * 86400:
  if os.path.isfile(full):
   d = os.stat(full).st_mtime
   print(full)
   print(datetime.utcfromtimestamp(d))
   print(" ")
   os.remove(os.path.join(path, f))

# Create the log file if it does not exist
try:
   with open(logfile): pass
except IOError:
 target = open (logfile, 'w')
 target.write("\n")
 target.close()

# Write to the log file
with open(logfile, "r+") as f:
 old = f.read() 
 f.seek(0)
 f.write("Job Complete - " + str(datetime.utcfromtimestamp(now)) + "\n" + old)
   
print("All Done")

No comments:

Post a Comment