Call shutil.rmtree(folder_path) from the built-in shutil module—which recursively removes every nested file, subdirectory, and symlink inside folder_path before removing the directory itself—whereas os.rmdir() and Path.rmdir() only delete completely empty folders and raise OSError: [Errno 39] Directory not empty if anything remains inside.
Basic Example
import shutil
from pathlib import Path
target_dir = Path("build_artifacts")
# 1. Recommended: Recursively delete a non-empty folder and everything inside it
if target_dir.exists():
shutil.rmtree(target_dir)
# 2. Ignore errors if the folder does not exist (Python 3.12+ `onexc=` or existence check):
shutil.rmtree(target_dir, ignore_errors=True)
Key Details & Edge Cases
shutil.rmtree()does NOT have anmissing_ok=Trueparameter (unlikePath.unlink()):- Calling
shutil.rmtree("nonexistent_dir")raisesFileNotFoundErrorunless you guard it withif target_dir.exists():(orcontextlib.suppress(FileNotFoundError)). Avoidignore_errors=Trueif you only want to suppress missing-directory errors, becauseignore_errors=Truealso silently swallows genuinePermissionErrorfailures on locked files.
- Calling
- Read-only files on Windows raise
PermissionError: [WinError 5] Access is denied(.gitobjects, etc.):- On Windows,
shutil.rmtree()refuses to delete files marked read-only (such as.git/objects/pack/*). Clear the read-only bit inside a callback before retryingos.unlink:import os import shutil import stat def remove_readonly(func, path, excinfo): os.chmod(path, stat.S_IWRITE) func(path) # Python 3.12+ uses `onexc=`; Python <= 3.11 uses `onerror=` (deprecated in 3.12): shutil.rmtree("repo_clone", onexc=remove_readonly)
- On Windows,
- Symlink safety (
shutil.rmtree()never traverses into symlinked directories):- By design,
shutil.rmtree()unlinks symbolic links to directories rather than following them and wiping external targets. However, passing a symlink itself as the top-levelpathargument raisesOSError: Cannot call rmtree on a symbolic link—checkif path.is_symlink(): path.unlink()first if the root target might be a symlink.
- By design,
- Avoid
os.system("rm -rf ...")orsubprocess.run(["rm", "-rf", ...]):- Shelling out to
rm -rffails on Windows (cmd.exelacksrm), introduces command-injection risks if paths contain spaces or shell metacharacters, and hides granular per-file exceptions.
- Shelling out to
- Clearing a directory’s contents without deleting the root folder itself:
- If you want to keep the empty parent directory (for example,
temp_uploads/), iterate overfor child in target_dir.iterdir():and callshutil.rmtree(child)ifchild.is_dir() and not child.is_symlink()elsechild.unlink().
- If you want to keep the empty parent directory (for example,
Comparison of Directory & File Deletion Methods in Python
| Method | Deletes Non-Empty Folders Recursively? | Deletes Single Files / Symlinks? | Cross-Platform (Windows + POSIX)? | Best Used When |
|---|---|---|---|---|
shutil.rmtree(path) (Recommended) |
Yes | No (NotADirectoryError on files) |
Yes | Deleting an entire directory tree along with all nested subdirectories and files. |
Path.rmdir() / os.rmdir() |
No (raises OSError: Directory not empty) |
No | Yes | Ensuring a folder is strictly empty before removing it so accidental data loss cannot occur. |
Path.unlink(missing_ok=True) |
No (IsADirectoryError / PermissionError) |
Yes (files and symlinks only) | Yes | Deleting individual files or symbolic links safely. |
shutil.rmtree(path, onexc=...) |
Yes | No | Yes (handles Windows read-only bits) | Removing folders containing read-only files (such as .git repositories on Windows). |
You must log in or register to comment.
