ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: remove directories recursively
Submitter: Dan Gunter (other recipes)
Last Updated: 2008/03/26
Version no: 1.0
Category: System

 

Not Rated yet


Description:

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.

Source: Text Source

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.



Add comment

Number of comments: 2

shutil.rmtree(), Simon Brunning, 2008/03/26
And the problem with shutil.rmtree() is?
Add comment

shutil.rmtree(), Kent Johnson,Kent Johnson, 2008/03/27
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)

Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. a friendly mkdir()

4. SOLVING THE METACLASS ...

5. Povray for python

6. Changing return value ...

7. Implementation of sets ...

8. bag collection class

9. deque collection class

10. Floating Point Simulator




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.