[Python] Removing a non-empty folder
Removing a non-empty folder
You will get an ‘access is denied’ error when you attempt to use
1 os.remove(“/folder_name”)
to delete a folder which is not empty. The most direct and efficient way to remove non-empty folder is like this:
1 import shutil 2 shutil.rmtree(“/folder_name”)
Of course you have other ways that might be less efficient such as use os.walk():
1 # Delete everything reachable from the directory named in 'top', 2 # assuming there are no symbolic links. 3 # CAUTION: This is dangerous! For example, if top == '/', it 4 # could delete all your disk files. 5 import os 6 for root, dirs, files in os.walk(top, topdown=False): 7 for name in files: 8 os.remove(os.path.join(root, name)) 9 for name in dirs: 10 os.rmdir(os.path.join(root, name))