recursively remove directories in python
April 2nd, 2007 by Lawrence David
if you try and use os.rmdir to remove a set of nested directories in python, you’ll receive the following error message:
OSError: [Errno 66] Directory not empty:
to skirt this problem, use the shutil module:
import shutil
shutil.rmtree(tree_name)
This fails if any files are read-only.
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.
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)