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

Check
remove_tree( directory[verbose=0, dry_run=0])
in module
distutils.dir_util

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.