To delete files and folders in Python, you can use the os
, shutil
, and pathlib
modules. Below is a detailed guide with examples covering various scenarios, error handling, and best practices.
Table of Contents
- Delete a File
- Using
os.remove()
- Using
pathlib.Path.unlink()
- Delete an Empty Folder
- Using
os.rmdir()
- Using
pathlib.Path.rmdir()
- Delete a Non-Empty Folder (Recursive)
- Using
shutil.rmtree()
- Advanced Examples
- Delete Multiple Files
- Delete Files Matching a Pattern (e.g.,
.tmp
) - Handle Read-Only Files (Windows)
- Error Handling
- Common Exceptions
- Cross-Platform Considerations
- Third-Party Options
- Send to Trash/Recycle Bin
1. Delete a File
Method 1: os.remove()
import os
file_path = "example.txt"
try:
os.remove(file_path)
print(f"✅ File '{file_path}' deleted.")
except FileNotFoundError:
print(f"⚠️ File '{file_path}' does not exist.")
except PermissionError:
print(f"❌ Permission denied for '{file_path}'. File may be in use or read-only.")
Method 2: pathlib.Path.unlink()
(Modern Approach)
from pathlib import Path
file = Path("example.txt")
if file.exists():
try:
file.unlink() # Delete the file
print(f"✅ File '{file}' deleted.")
except PermissionError:
print(f"❌ Permission denied for '{file}'.")
else:
print(f"⚠️ File '{file}' does not exist.")
2. Delete an Empty Folder
Method 1: os.rmdir()
import os
folder_path = "empty_folder"
try:
os.rmdir(folder_path)
print(f"✅ Folder '{folder_path}' deleted.")
except FileNotFoundError:
print(f"⚠️ Folder '{folder_path}' does not exist.")
except OSError as e:
print(f"❌ Error: {e}. Folder may not be empty.")
Method 2: pathlib.Path.rmdir()
from pathlib import Path
folder = Path("empty_folder")
if folder.exists() and folder.is_dir():
try:
folder.rmdir()
print(f"✅ Folder '{folder}' deleted.")
except OSError as e:
print(f"❌ Error: {e}.")
else:
print(f"⚠️ Folder '{folder}' does not exist.")
3. Delete a Non-Empty Folder (Recursive Deletion)
Use shutil.rmtree()
to delete a folder and all its contents:
import shutil
folder_path = "non_empty_folder"
try:
shutil.rmtree(folder_path)
print(f"✅ Folder '{folder_path}' and all contents deleted.")
except FileNotFoundError:
print(f"⚠️ Folder '{folder_path}' does not exist.")
except PermissionError:
print(f"❌ Permission denied for '{folder_path}'.")
4. Advanced Examples
Delete Multiple Files
import os
files_to_delete = ["file1.txt", "file2.txt", "file3.txt"]
for file in files_to_delete:
try:
os.remove(file)
print(f"✅ Deleted '{file}'.")
except Exception as e:
print(f"❌ Failed to delete '{file}': {e}")
Delete Files Matching a Pattern (e.g., .tmp
)
from glob import glob
import os
for file in glob("*.tmp"):
try:
os.remove(file)
print(f"✅ Deleted temporary file: {file}")
except Exception as e:
print(f"❌ Failed to delete {file}: {e}")
Handle Read-Only Files (Windows)
import os
import stat
file_path = "read_only_file.txt"
try:
# Remove read-only attribute on Windows
os.chmod(file_path, stat.S_IWRITE) # Make file writable
os.remove(file_path)
print(f"✅ Deleted read-only file: {file_path}")
except Exception as e:
print(f"❌ Error: {e}")
5. Error Handling
Common Exceptions
Exception | Cause |
---|---|
FileNotFoundError | File/folder does not exist. |
PermissionError | Insufficient permissions or file/folder is in use (Windows/Linux). |
OSError | Folder not empty (for os.rmdir() ). |
Cross-Platform Tips
- Windows: Files may be locked by other processes (e.g., open in an editor).
- Linux/macOS: Check user permissions with
os.access(path, os.W_OK)
.
6. Third-Party Options
Send to Trash/Recycle Bin
Use the send2trash
library for safer deletions (files go to trash instead of being permanently deleted):
# Install first: pip install send2trash
from send2trash import send2trash
file_path = "important_document.txt"
try:
send2trash(file_path)
print(f"✅ Moved '{file_path}' to trash.")
except Exception as e:
print(f"❌ Error: {e}")
Summary Table
Action | Method | Module | Notes |
---|---|---|---|
Delete a file | os.remove() | os | Raises FileNotFoundError if missing |
Delete a file (modern) | Path.unlink() | pathlib | Object-oriented approach |
Delete empty folder | os.rmdir() | os | Fails if folder is not empty |
Delete empty folder | Path.rmdir() | pathlib | Requires folder to exist and be empty |
Delete non-empty folder | shutil.rmtree() | shutil | Permanent deletion |
Safe deletion (trash) | send2trash() | send2trash | Requires third-party library |
Best Practices
- Check existence before deletion (optional, but useful for feedback).
- Handle exceptions to avoid crashes (e.g., files in use, permissions).
- Test paths to prevent accidental deletion (e.g., avoid
shutil.rmtree("/")
). - Prefer
pathlib
for modern, readable code (Python 3.4+).
By following these methods, you can safely manage file and folder deletions in Python!