recursively removing files and directories

Sick Monkey sickcodemonkey at gmail.com
Mon Apr 9 17:08:22 EDT 2007


Here is some code that could be useful....  It does not check the
directories for 0 files, but that shouldn't be too difficult to add.

#############################################
from os import listdir, unlink
from os.path import isdir, isfile, islink, join, getmtime
deldir = "C:\Some\Dir"
delFileType = ".txt"    # or You could use Regex.
# -------------------------------------
def del_entry(_name):
        try:
                if isdir(_name):
                        print "Do Nothing"
                else:
                        #print "now"
                        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,_action):
        if not isdir(_dir):
                print "%s is not a directory" % (_dir)
                return
        for file in listdir(_dir):
                path = join(_dir, file)
                if isdir(path):
                        list_dir(path, _action)
                else:
                        # isfile() or islink()
                        if path.rfind(delFileType) != -1:
                                #print path
                                _action(path)
# Run it
list_dir(deldir, del_entry)
#############################################


On 9 Apr 2007 11:44:10 -0700, bahoo <b83503104 at yahoo.com> wrote:
>
> Hi,
>
> I found a message on Jan 16, 2006 regarding the same topic, except
> that I wanted to remove only certain files that satisfy the format
> "ABC_XXX_XXX.dat", but not the other files.  Once the files are
> removed, if a folder becomes empty, I want to remove the folder as
> well.
>
> The solution to the Jan 16 2006 message required many lines of python
> code.  I was wondering if there is a simpler solution to my problem at
> hand, perhaps by using more specialized functions?
>
> Thanks!
> bahoo
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070409/d94e8b5e/attachment.html>


More information about the Python-list mailing list