How do I remove/delete a folder that is not empty with Python?
From the python docs on
# 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))
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:
What is the most effective way of removing/deleting a folder/directory that is not empty?
This example shows how to remove a directory tree on Windows where some of the files have their read-only bit set. It uses the onerror callback to clear the readonly bit and reattempt the remove. Any subsequent failure will propagate.
import os, stat import shutil def remove_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path) shutil.rmtree(directory, onerror=remove_readonly)
To delete a folder even if it might not exist (avoiding the race condition in Charles Chow's answer) but still have errors when other things go wrong (e.g. permission problems, disk read error, the file isn't a directory)
For Python 3.x:
import shutil def ignore_absent_file(func, path, exc_inf): except_instance = exc_inf if isinstance(except_instance, FileNotFoundError): return raise except_instance shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)
The Python 2.7 code is almost the same:
import shutil import errno def ignore_absent_file(func, path, exc_inf): except_instance = exc_inf if isinstance(except_instance, OSError) and \ except_instance.errno == errno.ENOENT: return raise except_instance shutil.rmtree(dir_to_delete, onerror=ignore_absent_file)
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 dir content, remove this line
pth is a
pathlib.Path instance. Nice, but may not be the fastest.
if you are sure, that you want to delete the entire dir tree, and are no more interested in contents of dir, then crawling for entire dir tree is stupidness... just call native OS command from python to do that. It will be faster, efficient and less memory consuming.
RMDIR c:\blah /s /q
rm -rf /home/whatever
In python, the code will look like..
import sys import os mswindows = (sys.platform == "win32") def getstatusoutput(cmd): """Return (status, output) of executing cmd in a shell.""" if not mswindows: return commands.getstatusoutput(cmd) pipe = os.popen(cmd + ' 2>&1', 'r') text = pipe.read() sts = pipe.close() if sts is None: sts = 0 if text[-1:] == '\n': text = text[:-1] return sts, text def deleteDir(path): """deletes the path entirely""" if mswindows: cmd = "RMDIR "+ path +" /s /q" else: cmd = "rm -rf "+path result = getstatusoutput(cmd) if(result!=0): raise RuntimeError(result)
If you don't want to use the
shutil module you can just use the
from os import listdir, rmdir, remove for i in listdir(directoryToRemove): os.remove(os.path.join(directoryToRemove, i)) rmdir(directoryToRemove) # Now the directory is empty of files