Advertisement
opexxx

clean_folder.py

Nov 26th, 2013
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1. #!/usr/bin/python
  2. ##
  3. # clean_folder  --  clean up temporary folders
  4. ##
  5. # Deletes everything under a folder which hasn't been modified
  6. # in a week. Deletes directories that are empty, too.
  7. ###
  8.  
  9. import os, sys, time
  10.  
  11. if (len(sys.argv) == 2) and (sys.argv[1] == '-d'):
  12.     dryrun = True
  13. else:
  14.     dryrun = False
  15.  
  16. tmpdir = '/home/danny/tmp'
  17. daysback = 7
  18. cutofftime  = time.time() - (60 * 60 * 24 * daysback)
  19.  
  20. for d in os.walk(tmpdir, topdown=False):
  21.     (dirpath, dirnames, filenames) = d
  22.     for f in filenames:
  23.         thisfile = os.path.join(dirpath, f)
  24.         if (os.lstat(thisfile).st_mtime < cutofftime):
  25.             try:
  26.                 if dryrun:
  27.                     print "I would delete:", thisfile
  28.                 else:
  29.                     os.remove(thisfile)
  30.             except OSError, (errno, strerror):
  31.                 print "%s: OSError(%s): %s" % (d, errno, strerror)
  32.  
  33.     for d in dirnames:
  34.         thisdir = os.path.join(dirpath, d)
  35.         if not os.listdir(thisdir):
  36.             try:
  37.                 if dryrun:
  38.                     print "I would delete:", thisfile
  39.                 else:
  40.                     os.rmdir(thisdir)
  41.             except OSError, (errno, strerror):
  42.                 if (errno != 66):
  43.                     print "%s: OSError(%s): %s" % (d, errno, strerror)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement