HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
replaceemptyhowdeleteremovefoldernotthat

Problem

I am getting an "access is denied" error when I attempt to delete a folder that is not empty. Newer versions of Python may also report a "directory not empty" error.

I used the following command in my attempt:
os.remove("/folder_name")


How can I remove, delete, or replace a directory that is not empty?

Solution

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)

Code Snippets

import shutil

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

Context

Stack Overflow Q#303200, score: 1829

Revisions (0)

No revisions yet.