Use Path.unlink(missing_ok=True) from Python’s built-in pathlib module to safely delete a single file without raising an error if it doesn’t exist, and shutil.rmtree() to delete a non-empty folder and all its contents.

Basic Example

from pathlib import Path
import shutil

# 1. Safely delete a single file (no error if the file is already missing)
file_path = Path("temp/report.txt")
file_path.unlink(missing_ok=True)

# 2. Safely delete an empty directory
empty_dir = Path("temp/empty_folder")
if empty_dir.exists() and empty_dir.is_dir():
    empty_dir.rmdir()  # Only works if the directory is completely empty

# 3. Delete a non-empty directory and everything inside it
folder_path = Path("temp/build_artifacts")
if folder_path.exists():
    shutil.rmtree(folder_path)

Key Details & Safety Practices

  • Preventing FileNotFoundError (missing_ok=True): Added in Python 3.8, file_path.unlink(missing_ok=True) avoids race conditions (TOCTOU bugs) where a file is deleted between an if path.exists(): check and the deletion call.
  • Deleting non-empty folders safely (shutil.rmtree): Both os.rmdir() and Path.rmdir() raise an OSError if the directory contains any files or subfolders. shutil.rmtree() deletes everything recursively—verify the target path first (e.g., check path.is_dir()) so you never accidentally pass an unintended root or parent path.
  • Handling read-only files on Windows (onerror / onexc): On Windows, shutil.rmtree() raises a PermissionError if a file inside the folder is marked read-only (common in .git folders). In Python 3.12+, handle this using the onexc callback:
    import os
    import shutil
    import stat
    
    def handle_readonly(func, path, exc):
        os.chmod(path, stat.S_IWRITE)
        func(path)
    
    shutil.rmtree("repo_copy", onexc=handle_readonly)
    
  • Moving to the system Trash/Recycle Bin (send2trash): Because unlink() and rmtree() bypass the Recycle Bin and permanently delete data immediately, use the third-party send2trash library (pip install send2trash) when deleting user-facing files that might need recovery.

Comparison of Deletion Functions

Function / Method Target Type Works on Non-Empty Folders? Fails if Missing? Permanent Deletion?
Path.unlink(missing_ok=True) File or symlink No (IsADirectoryError) No Yes
os.remove(path) File or symlink No (IsADirectoryError) Yes (FileNotFoundError) Yes
Path.rmdir() / os.rmdir() Empty directory only No (OSError) Yes (FileNotFoundError) Yes
shutil.rmtree(path) Directory tree Yes (recursive) Yes (FileNotFoundError) Yes
send2trash.send2trash(path) File or directory Yes Yes No (moves to Trash)