0

So I was thinking that there would be a simple Pythonic way to delete a directory structure. My app creates and deletes user accounts, which may contain any number of subdirectories and files. Hence, I wanted to do something like:

os.rmdir(user_directory)

BUT...that throws an error when user_directory is non-empty. So then I looked at os.removedirs(), but it recurses *up* the tree, which means that I would have to find the bottom. So I ended up rolling my own:

def remove_recurse(path):
        """equivalent to rm -rf path"""
        for i in os.listdir(path):
            full_path = path + "/" + i
            if os.path.isdir(full_path):
                remove_recurse(full_path)
            else:
                os.remove(full_path)
        os.rmdir(path)

which I believe to be correct. But why is such a function not a part of the os module ... or is it?

Thanks,
Jeff Cagle

3
Contributors
2
Replies
3
Views
11 Years
Discussion Span
Last Post by pythonista
0

shutil.rmtree(path[, ignore_errors[, onerror]]) from module shutil removes directories and files recursively.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.