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.
views:
5752answers:
2Definitely the right way.
Loki
2008-11-19 20:27:12
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
2010-04-16 22:02:22
+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
2008-11-19 20:23:41
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
2008-11-19 20:25:21
Its ok, I'm still learning the site =/. If People want best practice... docs... personal experience etc.
kkubasik
2008-11-19 20:30:00
Well, maybe I'm wrong of downmodding. But I can, right now I think it's right.
ddaa
2008-11-19 20:39:12
@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
2008-11-19 21:18:11
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
2008-11-19 21:50:48