Is there a library equivalent of "rm -rf" ?

Trent Mick trentm at ActiveState.com
Wed Oct 30 18:11:37 EST 2002


[Andrew Koenig wrote]
> I couldn't find a library function to (recursifely) remove a directory
> and everything in it.
> 
> os.rmdir removes a directory, but only if it's empty.
> 
> os.removedirs removes a file, then pruns empty directories above it.

There is shutil.rmtree().

I use the following enable removing trees that include read-only files:

     def _rmtreeOnError(rmFunction, filePath, excInfo):
         if excInfo[0] == OSError:
             # presuming because file is read-only
             os.chmod(filePath, 0777)
             rmFunction(filePath)
     
     def rmtree(dirname):
         import shutil
         shutil.rmtree(dirname, 0, _rmtreeOnError)

Cheers,
Trent


-- 
Trent Mick
TrentM at ActiveState.com




More information about the Python-list mailing list