Welcome, guest | Sign In | My Account | Store | Cart

Extremely simple bit of code to remove a directory recursively. Simply feed it the path of the top-level directory to remove, and off it goes. As presented, there is no error-checking; failure at any point will stop the function and raise an IOError.

Python, 8 lines
1
2
3
4
5
6
7
8
import os
def rm_rf(d):
    for path in (os.path.join(d,f) for f in os.listdir(d)):
        if os.path.isdir(path):
            rm_rf(path)
        else:
            os.unlink(path)
    os.rmdir(d)

I came across a need to do this in a regression test. The lack of error-checking was fine in this case, where the directory tree in question is just a bunch of stuff created in /tmp.

2 comments

Simon Brunning 16 years, 1 month ago  # | flag

shutil.rmtree(). And the problem with shutil.rmtree() is?

Kent Johnson 16 years, 1 month ago  # | flag

shutil.rmtree(). I find it annoying that rmtree() fails if the directory doesn't exist. Here is my version:

def removeDir(path):
    if os.path.isdir(path):
        shutil.rmtree(path)
Created by Dan Gunter on Wed, 26 Mar 2008 (PSF)
Python recipes (4591)
Dan Gunter's recipes (1)

Required Modules

Other Information and Tasks