Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove/delete a folder that is not empty?

Tags:

python

file

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?

like image 600
Amara Avatar asked Nov 19 '08 20:11

Amara


People also ask

How do I force delete a full folder?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.

What is a non-empty directory?

The non-empty directory means the directory with files or subdirectories. We can delete the directory by using the Delete() method of the Directory class.


2 Answers

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) 
like image 96
ddaa Avatar answered Sep 23 '22 12:09

ddaa


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)) 
like image 42
kkubasik Avatar answered Sep 25 '22 12:09

kkubasik