How do I remove/delete a folder that is not empty?
import shutil
shutil.rmtree(dest, ignore_errors=True)
From the python docs on os.walk()
:
# 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))
import shutil
shutil.rmtree('/folder_name')
Standard Library Reference: shutil.rmtree.
By design, rmtree
fails on folder trees containing read-only files. If you want the folder to be deleted regardless of whether it contains read-only files, then use
shutil.rmtree('/folder_name', ignore_errors=True)
from python 3.4 you may use :
import pathlib
def delete_folder(pth) :
for sub in pth.iterdir() :
if sub.is_dir() :
delete_folder(sub)
else :
sub.unlink()
pth.rmdir() # if you just want to delete the dir content but not the dir itself, remove this line
where pth
is a pathlib.Path
instance. Nice, but may not be the fastest.