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

Discussion in 'Python' started by kbass, Nov 13, 2003.

  1. kbass

    kbass Guest

    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 '{}' \;

    kbass, Nov 13, 2003
    1. Advertisements

  2. 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
    =?ISO-8859-1?Q?Gerhard_H=E4ring?=, Nov 13, 2003
    1. Advertisements

  3. 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:

    The path module is available at

    -- Graham
    Graham Fawcett, Nov 13, 2003
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.