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

K

kbass

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
 
?

=?ISO-8859-1?Q?Gerhard_H=E4ring?=

kbass said:
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
 
G

Graham Fawcett

kbass said:
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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top