Deleting files and directory trees requires appropriate OS safety guards to handle permission errors and missing path exceptions gracefully.
pathlib.Path.unlink(missing_ok=True): Removes a single file or symbolic link.os.remove(path): Low-level file removal.os.rmdir(path): Removes an empty directory.shutil.rmtree(path): Recursively deletes an entire directory tree.from pathlib import Path
import shutil
def safe_delete_file(file_path: Path) -> bool:
"""Safely delete a single file using pathlib."""
try:
file_path.unlink(missing_ok=True) # Python 3.8+ missing_ok parameter
print(f"Successfully unlinked: {file_path}")
return True
except PermissionError:
print(f"Permission denied attempting to remove: {file_path}")
return False
def safe_delete_directory(dir_path: Path) -> None:
"""Recursively delete a directory directory tree safely."""
if dir_path.exists() and dir_path.is_dir():
shutil.rmtree(dir_path)
print(f"Recursively deleted directory: {dir_path}")
if __name__ == "__main__":
temp_dir = Path("temp_delete_test")
temp_dir.mkdir(exist_ok=True)
temp_file = temp_dir / "sample.txt"
temp_file.write_text("Delete me", encoding="utf-8")
safe_delete_file(temp_file)
safe_delete_directory(temp_dir)
missing_ok=True: pathlib.Path.unlink(missing_ok=True) eliminates boilerplate if file.exists(): checks.shutil.rmtree() Danger: shutil.rmtree() irreversibly deletes all contents inside a directory. Double-check path variables before execution.PermissionError: File locks on Windows cause PermissionError exceptions if the file is currently open in another process.Write a script that creates a temporary file temp.txt and immediately deletes it using unlink(missing_ok=True).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With