Function in shutil to clear contents of a directory

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): os.remove(fn) else: shutil.rmtree(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? Regards, Vinay Sajip

On Thu, Nov 01, 2012 at 12:24:37AM +0000, Vinay Sajip <vinay_sajip@yahoo.co.uk> wrote:
1. Perhaps the best way to achieve that is to add a parameter (a flag) to shutil.rmtree that would make rmtree to (not) remove the very path; by default it must be True to be backward-compatible. 2.
There are other filesystem objects besides files and links. I think it would be better to test for directory: if not os.path.isdir(fn):
rmtree, BTW, does the same. Oleg. -- Oleg Broytman http://phdru.name/ phd@phdru.name Programmers don't die, they just GOSUB without RETURN.

On Thu, Nov 01, 2012 at 12:24:37AM +0000, Vinay Sajip <vinay_sajip@yahoo.co.uk> wrote:
1. Perhaps the best way to achieve that is to add a parameter (a flag) to shutil.rmtree that would make rmtree to (not) remove the very path; by default it must be True to be backward-compatible. 2.
There are other filesystem objects besides files and links. I think it would be better to test for directory: if not os.path.isdir(fn):
rmtree, BTW, does the same. Oleg. -- Oleg Broytman http://phdru.name/ phd@phdru.name Programmers don't die, they just GOSUB without RETURN.
participants (2)
-
Oleg Broytman
-
Vinay Sajip