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.
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.
shutil.rmtree(). And the problem with shutil.rmtree() is?
shutil.rmtree(). I find it annoying that rmtree() fails if the directory doesn't exist. Here is my version: