Looks like you're only deleting files, with the "if not os.path.isdir(path)" line.  But beyond that, I think there's a problem with the order in which os.path.walk will call your lister.  walk() will call lister from top-down, whereas a delete type function like this needs to walk from bottom up.
 
Problem simpler to write your own little recursive thingy.
 
Or, you could cheat. 
  • Take out the directory check mentioned above
  • Attempt to delete all files, dir or file alike.
  • Catch and ignore the 'directory not empty' errors
  • Keep looping from the top until there's nothing left.
 
 
-----Original Message-----
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED]]On Behalf Of Adam Getchell
Sent: Sunday, May 12, 2002 1:50 AM
To: [EMAIL PROTECTED]
Subject: Shell tool

Hello all,

 

I’ve just started trying to use Python to automate Windows system administration. I wrote my first (long-winded, amateurish) shell-tool to os.path.walk through a directory structure and delete files older than 2 days. (Keeps users from cluttering some temporary storage space). It works fine, except that it does not delete the empty directories. Any hints?

 

"""Delete files older than AGING constant using os.path.walk"""

import sys, os, time

 

AGING = 172800  # Default 2 days

 

def lister(dummy, dirName, filesInDir):

    print '[' + dirName + ']'

    for fname in filesInDir:

        path = os.path.join(dirName, fname)

        if not os.path.isdir(path):

            print path, time.ctime(os.stat(path).st_mtime), fileage(path), prune(path)

            purge(path)

 

def fileage(file):

    curtime = time.time()

    modtime = os.stat(file).st_mtime

    age = curtime - modtime

    return age

 

def prune(file):

    if fileage(file) > AGING:

        return ("T")

    else:

        return ("File should not be deleted")

 

def purge(file):

    if prune(file) == "T":

        os.remove(file)       

   

 

if __name__ == '__main__':

    os.path.walk(sys.argv[1], lister, None)

 

--Adam Getchell

Reply via email to