[Python-ideas] Function in shutil to clear contents of a directory

Vinay Sajip vinay_sajip at yahoo.co.uk
Thu Nov 1 01:24:37 CET 2012

A couple of times recently on different projects, I've had the need to clear out
the contents of an existing directory. There doesn't appear to be any function
in shutil to do this. I've used

def clear_directory(path):
    for fn in os.listdir(path):
        fn = os.path.join(path, fn)
        if os.path.islink(fn) or os.path.isfile(fn):

One could just do shutil.rmtree(path) followed by os.mkdir(path), but that fails
if path is a symlink to a directory (disallowed by rmtree).

Is there some other obvious way to do this that I've missed? If not, I'd like to
see something like this added to shutil. What say?


Vinay Sajip

More information about the Python-ideas mailing list