Deleting Directories

L

Laura McCord

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
 
M

moma

Laura said:
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)
 

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,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top