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 anif path.exists():check and the deletion call. - Deleting non-empty folders safely (
shutil.rmtree): Bothos.rmdir()andPath.rmdir()raise anOSErrorif the directory contains any files or subfolders.shutil.rmtree()deletes everything recursively—verify the target path first (e.g., checkpath.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 aPermissionErrorif a file inside the folder is marked read-only (common in.gitfolders). In Python 3.12+, handle this using theonexccallback: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): Becauseunlink()andrmtree()bypass the Recycle Bin and permanently delete data immediately, use the third-partysend2trashlibrary (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) |
You must log in or register to comment.