tags:

views:

5752

answers:

2

I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: os.remove("/folder_name"). What is the most effective way of removing/deleting a folder/directory that is not empty? Thanks in advance.

+21  A: 
import shutil

shutil.rmtree('/folder_name')

Standard Library Reference: shutil.rmtree.

ddaa
Definitely the right way.
Loki
Note that `rmtree` will fail if there are read-only files: http://stackoverflow.com/questions/2656322/shutil-rmtree-fails-on-windows-with-access-is-denied
Sridhar Ratnakumar
+8  A: 

From the python docs:

# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))
kkubasik
Hi Kevin. This is a nice educational example, but practically the pythonic thing to do is using shutil.rmtree. Sorry, I have to downmod you.
ddaa
Its ok, I'm still learning the site =/. If People want best practice... docs... personal experience etc.
kkubasik
Well, maybe I'm wrong of downmodding. But I can, right now I think it's right.
ddaa
@ddaa: While using shutil is definitely the easiest way, there's certainly nothing unpythonic about this solution. I wouldn't have upvoted this answer, but I have this time only to cancel out your downvote :)
Jeremy Cantrell
The code itself is pythonic. Using it instead of shutil.rmtree in a real program would be unpythonic: that would be ignoring the "one obvious way of doing it". Anyway, this is semantics, removing the downmod.
ddaa
I upmodded you just because sticklers annoy me. :)
fivebells
*dicts "stickler"* Oh, hum. I think I might make this my middle name! :)
ddaa