rm -rf in python

David Allen s2mdalle at titan.vcu.edu
Sat Feb 24 15:56:35 EST 2001


I need to write the equivalent of "rm -rf" in python,
so I wrote this, but I'm having a hard time understanding
why it's not working.  

The assumptions that I'm working off of is that
os.rmdir() will fail on a non-empty directory, and
that os.unlink() will fail on a directory.  Here's
the code:

import dircache
import os

def recursive_delete(dirname):
    """Recursively deletes everything under dirname.  This does NOT make any
    symlink distinctions or otherwise, it's functionally equivalent to an
    rm -rf dirname so use it with much care."""
    try:
        print "Removing directory:  \"%s\"" % dirname
        os.rmdir(dirname)                            
    except OSError:        # Directory isn't empty.
        files = dircache.listdir(dirname)

        for file in files:
            # Get full pathname...
            file = "%s%s%s" % (dirname, os.sep, file)
            if os.path.isdir(file):
                return recursive_delete(file)
            else:
                print "Removing file:  \"%s\"" % file
                retval = os.unlink(file)
                return file

        # We've nuked all the files, now kill the directory.
        try:
            os.rmdir(dirname)
        except OSError:
            print "Wuh?  Huh?"

This prints out the actual filenames such as...

Removing file "/home/user/blarg/snuge.txt"

and so on, but the file actually still exists after
the program runs.  The module documentation in python
doesn't say anything about any particular return
value signaling an error and not being able to delete
a file, and all of these calls seem to be returning
None.  I've programmed in C before, and these syscalls
should return 0 for success, and != 0 otherwise,
but does that hold in python?

Any help would be appreciated.
-- 
David Allen
http://opop.nols.com/
----------------------------------------
Alliance, n.: 
In international politics, the union of two thieves who have 
their hands so deeply inserted in each other's pocket that they cannot 
separately plunder a third. 
- Ambrose Bierce, "The Devil's Dictionary"



More information about the Python-list mailing list