How do you delete a non-empty folder and all its contents in Python? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you delete a non-empty folder and all its contents in Python?

message-square
0

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 an missing_ok=True parameter (unlike Path.unlink()):
    • Calling shutil.rmtree("nonexistent_dir") raises FileNotFoundError unless you guard it with if target_dir.exists(): (or contextlib.suppress(FileNotFoundError)). Avoid ignore_errors=True if you only want to suppress missing-directory errors, because ignore_errors=True also silently swallows genuine PermissionError failures on locked files.
  • Read-only files on Windows raise PermissionError: [WinError 5] Access is denied (.git objects, 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 retrying os.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)
      
  • 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-level path argument raises OSError: Cannot call rmtree on a symbolic link—check if path.is_symlink(): path.unlink() first if the root target might be a symlink.
  • Avoid os.system("rm -rf ...") or subprocess.run(["rm", "-rf", ...]):
    • Shelling out to rm -rf fails on Windows (cmd.exe lacks rm), introduces command-injection risks if paths contain spaces or shell metacharacters, and hides granular per-file exceptions.
  • 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 over for child in target_dir.iterdir(): and call shutil.rmtree(child) if child.is_dir() and not child.is_symlink() else child.unlink().

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