Deleting Directories
moma
moma at example.net
Fri May 21 12:09:22 EDT 2004
Laura McCord wrote:
> Hi,
>
> I need to delete all directories in /var/www/html/test that are older
> than five days. I am new to python so how would I get started? Any tips
> or suggestions would be appreciated.
>
> Thanks,
> Laura
>
Hello Laura,
Use walk() or listdir() to traverse thru all files in your directory.
The following excerpt is a skeleton, untested code. It tests
modified_date and can delete both files and directories.
Note: rmdir() and unlink() is commented out.
www.google.com has several examples.
Search for "python walk and (dir or listdir)"
// moma
python newb
http://www.futuredesktop.org
#!/usr/bin/python -u
import sys, time
from os import listdir, unlink
from os.path import isdir, isfile, islink, join, getmtime
deldir = "/home/moma/tmp"
days = 5
now = int(time.time())
deldate = now - (days * 24 * 60 * 60)
# -------------------------------------
def del_entry(_name):
try:
if isdir(_name):
# rmdir(_name)
sys.stdout.write("Delete DIR %s\n" % (_name))
else:
# unlink(_name) # or remove(_name)
sys.stdout.write("Delete FILE %s\n" % (_name))
except IOError:
sys.stderr.write("Cannot delete %s\n" % (_name))
# -------------------------------------
def list_dir(_dir, _date, _action):
if not isdir(_dir):
print "%s is not a directory" % (_dir)
return
# if getmtime(_dir) > _date: return
for file in listdir(_dir):
path = join(_dir, file)
if getmtime(path) > _date: continue
if isdir(path):
list_dir(path, _date, _action)
_action(path)
else:
# isfile() or islink()
_action(path)
// Run it
list_dir(deldir, deldate, del_entry)
More information about the Python-list
mailing list