Newby Question: Remove files older than 7 days from a directory

Gerhard Häring gh at ghaering.de
Thu Nov 13 05:36:45 EST 2003


kbass wrote:
> I would like to remove file that are older than 7 days old from a directory.
> I can do this in shell script rather easy but I would like to integrate this
> functionality into my Python program. How can this be achieved? Which module
> can be used to perform this tasks? Thanks!
> 
> Shell Script example:   find /path/to/dir -mtime +30 -exec rm '{}' \;

Here's a short example:

import os, time

path = r"c:\tmp"
now = time.time()
for f in os.listdir(path):
     if os.stat(f).st_mtime < now - 7 * 86400:
         if os.path.isfile(f):
             os.remove(os.path.join(path, f))

-- Gerhard





More information about the Python-list mailing list