os.removedirs not working

Christopher T King squirrel at WPI.EDU
Thu Aug 12 11:33:38 EDT 2004


On Thu, 12 Aug 2004, Golawala, Moiz M (GE Infrastructure) wrote:

> I have a small program that where I am using
> os.removedirs('C:\\someDir') on windows. I get the error that the
> directory is not empty. Sure there are sub-directories under it and all
> file and directories are deletable(nothing is locked by the system) and
> there are no permission issues either. Can someone please tell me if I
> am using the os.removedirs() correctly?

os.removedirs() won't remove files for you.  As far as I can tell, there's
no builtin Python function that does this, but the library docs for os
give the following bit of code that does just what you want:

 import os
 from os.path import join
 # Delete everything reachable from the directory named in 'top'.
 # CAUTION:  This is dangerous!  For example, if top == '/', it
 # could delete all your disk files.
 for root, dirs, files in os.walk(top, topdown=False):
     for name in files:
         os.remove(join(root, name))
     for name in dirs:
         os.rmdir(join(root, name))

My guess as to why this isn't a library function is precisely the reason 
stated in that comment: it's potentially dangerous!




More information about the Python-list mailing list