ActiveState Code

Recipe 552732: remove directories recursively


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
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)

Discussion

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.

Comments

  1. 1. At 4:48 p.m. on 26 mar 2008, Simon Brunning said:

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

  2. 2. At 5:24 a.m. on 27 mar 2008, Kent Johnson said:

    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)
    

Sign in to comment