[Python] Removing a non-empty folder

时间:2023-03-09 06:45:55
[Python] Removing a non-empty folder

Removing a non-empty folder

You will get an ‘access is denied’ error when you attempt to use

 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:

 import shutil
shutil.rmtree(“/folder_name”)

Of course you have other ways that might be less efficient such as use 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))