Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

delete all files in a dir created last week

Status
Not open for further replies.

tnbobbie

Programmer
Nov 11, 2003
1
0
0
IN
Hi all
I'm new to python.
Can some one help me in writing a script, that deletes all the files whose age is more that a week in a directory?
Is this possible?
plz help me
tnx
bobbie
 
Yes... it's definitely possible.
You'll want to combine the following:

* Some way of looping over the files in that directory.
I would recommend using os.walk (new in Python 2.3).
For an example of using os.walk, see
(bottom of the page).

* Some way of testing the age of the files. I would
suggest os.stat (eg: os.stat('filename').st_mtime.
You'll also want to compare this with current time
and see if the difference is over 7 days...
time.time() returns current time, and
datetime.timedelta provides a handy way to compare
time intervals.

Here's some sample code:
>>> filename = 'c:/local_documents/temp/demo.py'
>>> ageOfFileInSec = time.time() - os.stat(filename).st_mtime
>>> ageOfFile = datetime.timedelta(seconds = ageOfFileInSec)
>>> oneWeek = datetime.timedelta(days = 7)
>>> ageOfFile > oneWeek
True

* Some way of deleting a file. I suggest os.remove().

Hope this helps! Write me at mcherm@mcherm.com if you need more hints with this.

-- Michael Chermside
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top