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

Oleg Broytman phd at phdru.name
Thu Nov 1 04:08:08 CET 2012


On Thu, Nov 01, 2012 at 12:24:37AM +0000, Vinay Sajip <vinay_sajip at yahoo.co.uk> wrote:
> 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?

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.

> 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):

   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):
>             os.remove(fn)
>         else:
>             shutil.rmtree(fn)

   rmtree, BTW, does the same.

Oleg.
-- 
     Oleg Broytman            http://phdru.name/            phd at phdru.name
           Programmers don't die, they just GOSUB without RETURN.



More information about the Python-ideas mailing list