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

Graham Fawcett graham__fawcett at hotmail.com
Thu Nov 13 14:52:27 EST 2003


"kbass" <kbass at midsouth.rr.com> wrote in message news:<i2Jsb.30120$oC5.11707 at clmboh1-nws5.columbus.rr.com>...
> 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 '{}' \;
> 
> 
> Kevin

Well, one way would be 

    import os
    os.system("find /path/to/dir -mtime +30 -exec rm '{}' \;")

but that's cheating (and non-portable, of course).

Gerhard's code is a great example, but it won't recurse into
subdirectories like the find command does. For that you need the
os.path.walk() or (in Python 2.3) the os.walk() function. The
os.path.walk() version is notorious for its counterinuitiveness, hence
the newer, friendlier version in the os module.

I'd gladly recommend Joe Orendorff's 'path' module, which doesn't come
with the Python Standard Library, but which you can download and
include either in your site-packages directory, or just put it in the
same directory as your application. The path module takes a more
object-oriented approach than the walk() variants in the standard
library. Example:

    import time
    from path import path

    seven_days_ago = time.time() - 7 * 86400   
    base = path('/path/to/dir')

    for somefile in base.walkfiles():
        if somefile.mtime < seven_days_ago:
            somefile.remove()


The path module is available at 
http://www.jorendorff.com/articles/python/path/

-- Graham




More information about the Python-list mailing list