os.rmdir() and os.removedirs() only work on empty directories?

Ben Hutchings ben.hutchings at roundpoint.com
Tue Dec 5 11:05:28 EST 2000


jschmitt at vmlabs.com writes:

> I was a bit surprised to find that os.rmdir() and os.removedirs() both
> complained if I tried to delete a directory that was not empty.  Is
> that expected?

POSIX says the rmdir call should only remove an empty directory, so it
doesn't surprise me that os.rmdir behaves this way.  I have yet to see
what os.removedirs is for.

> I guess shutil.rmtree() is the tool to use if I really want to
> recursively delete a directory hierarchy that is non-empty.

I hadn't seen that one - I wrote this function myself when I wanted
recursive deletion:

def rmdir_recursive(dir):
    """Remove a directory, and all its contents if it is not already empty."""
    for name in os.listdir(dir):
        full_name = os.path.join(dir, name)
        # on Windows, if we don't have write permission we can't remove
        # the file/directory either, so turn that on
        if not os.access(full_name, os.W_OK):
            os.chmod(full_name, 0600)
        if os.path.isdir(full_name):
            rmdir_recursive(full_name)
        else:
            os.remove(full_name)
    os.rmdir(dir)

> I don't quite understand this part of the documentation os.removedirs():
> '...if the leaf directory is successfully removed, directories
> corresponding to rightmost path segments will be pruned way until
> either the whole path is consumed...'

I believe that this means it will remove successive parent directories
referred to in the given path if they have become empty - so if you have
the following directory structure:

    . (current directory)
    |
    +--a/
    |  |
    |  +--b/
    |  |  |
    |  |  +--c/
    |  |     |
    |  |     +--d/
    |  |
    |  +--e/
    |
    +--f

and you call os.removedirs('a/b/c/d'), it will remove directories
a/b/c/d, a/b/c and a/b (assuming the process is permitted to do so).
It will attempt to remove a, fail because a is not empty, and then
stop.

-- 
Any opinions expressed are my own and not necessarily those of Roundpoint.



More information about the Python-list mailing list