Coder Perfect

How can I delete or remove a non-empty folder?

Problem

When I try to delete a folder that isn’t empty, I get a ‘access is denied’ error. In my attempt, I used the command os.remove(“/folder name”).

What is the most efficient approach to remove/delete a non-empty folder/directory?

Asked by Amara

Solution #1

import shutil

shutil.rmtree('/folder_name')

Standard Library Reference: shutil.rmtree.

Rmtree is designed to fail on folder trees that contain read-only files. Use this option if you wish to delete the folder regardless of whether it contains read-only files.

shutil.rmtree('/folder_name', ignore_errors=True)

Answered by ddaa

Solution #2

The following is taken from the os.walk() documentation in Python:

# 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))

Answered by kkubasik

Solution #3

import shutil
shutil.rmtree(dest, ignore_errors=True)

Answered by Siva Mandadi

Solution #4

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

pth refers to a pathlib. Instance of a path It’s nice, but it’s not the fastest.

Answered by yota

Solution #5

From docs.python.org:

Answered by Dave Chandler

Post is based on https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty