REMOVING FILES AND DIRECTORIES - Using os.remove() and os.rmdir()
Python
#!/usr/bin/env python3
"""
REMOVING FILES AND DIRECTORIES - Using os.remove() and os.rmdir()
Demonstrates safe file and directory deletion
"""
import os
import tempfile
import shutil
print("=" * 60)
print("REMOVING FILES AND DIRECTORIES")
print("=" * 60)
temp_dir = tempfile.gettempdir()
test_dir = os.path.join(temp_dir, "remove_demo")
os.makedirs(test_dir, exist_ok=True)
print(f"Created test directory: {test_dir}\n")
# Example 1: Basic os.remove() for files
print("1. Basic os.remove() - Delete File")
print("-" * 40)
test_file = os.path.join(test_dir, "delete_me.txt")
with open(test_file, 'w') as f:
f.write("This file will be deleted\n")
print(f" Created: {test_file}")
print(f" Exists before: {os.path.exists(test_file)}")
os.remove(test_file)
print(f" Exists after: {os.path.exists(test_file)}")
# Example 2: os.rmdir() for empty directories
print("\n2. os.rmdir() - Remove Empty Directory")
print("-" * 40)
empty_dir = os.path.join(test_dir, "empty_directory")
os.mkdir(empty_dir)
print(f" Created: {empty_dir}")
print(f" Exists before: {os.path.exists(empty_dir)}")
os.rmdir(empty_dir)
print(f" Exists after: {os.path.exists(empty_dir)}")
# Example 3: rmdir() fails on non-empty directory
print("\n3. rmdir() Fails on Non-Empty Directory")
print("-" * 40)
non_empty_dir = os.path.join(test_dir, "non_empty")
os.mkdir(non_empty_dir)
# Add a file to it
with open(os.path.join(non_empty_dir, "file.txt"), 'w') as f:
f.write("content")
try:
os.rmdir(non_empty_dir)
except OSError as e:
print(f" Error: {e}")
print(" rmdir() only works on empty directories")
# Example 4: Safe file removal with exists check
print("\n4. Safe File Removal with Existence Check")
print("-" * 40)
def safe_remove_file(filepath):
"""Safely remove file if it exists"""
if os.path.exists(filepath):
os.remove(filepath)
print(f" Removed: {filepath}")
return True
else:
print(f" File doesn't exist: {filepath}")
return False
test_file2 = os.path.join(test_dir, "test.txt")
with open(test_file2, 'w') as f:
f.write("test")
safe_remove_file(test_file2)
safe_remove_file(test_file2) # Try again
# Example 5: Remove multiple files
print("\n5. Remove Multiple Files")
print("-" * 40)
files_to_remove = []
for i in range(5):
filepath = os.path.join(test_dir, f"file{i}.txt")
with open(filepath, 'w') as f:
f.write(f"Content {i}")
files_to_remove.append(filepath)
print(f" Created {len(files_to_remove)} files")
for filepath in files_to_remove:
os.remove(filepath)
print(f" Removed: {os.path.basename(filepath)}")
# Example 6: Remove files by pattern
print("\n6. Remove Files by Pattern (*.log)")
print("-" * 40)
# Create log files
log_files = ["app.log", "error.log", "debug.log"]
for logfile in log_files:
filepath = os.path.join(test_dir, logfile)
with open(filepath, 'w') as f:
f.write("Log content")
print(f" Created {len(log_files)} log files")
# Remove all .log files
removed_count = 0
for filename in os.listdir(test_dir):
if filename.endswith('.log'):
filepath = os.path.join(test_dir, filename)
os.remove(filepath)
removed_count += 1
print(f" Removed {removed_count} .log files")
# Example 7: Remove old files (by modification time)
print("\n7. Remove Old Files (Simulated)")
print("-" * 40)
import time
# Create files with different times
old_file = os.path.join(test_dir, "old.txt")
new_file = os.path.join(test_dir, "new.txt")
with open(old_file, 'w') as f:
f.write("old")
time.sleep(0.01)
with open(new_file, 'w') as f:
f.write("new")
# Get file ages
old_mtime = os.path.getmtime(old_file)
new_mtime = os.path.getmtime(new_file)
print(f" old.txt modification time: {old_mtime}")
print(f" new.txt modification time: {new_mtime}")
# Remove older file
if old_mtime < new_mtime:
os.remove(old_file)
print(f" Removed older file: old.txt")
os.remove(new_file)
# Example 8: Remove directory tree with shutil
print("\n8. Remove Directory Tree (shutil.rmtree)")
print("-" * 40)
tree_dir = os.path.join(test_dir, "tree")
os.makedirs(os.path.join(tree_dir, "sub1", "sub2"))
with open(os.path.join(tree_dir, "file.txt"), 'w') as f:
f.write("test")
with open(os.path.join(tree_dir, "sub1", "file.txt"), 'w') as f:
f.write("test")
print(f" Created directory tree with files")
print(f" Exists before: {os.path.exists(tree_dir)}")
shutil.rmtree(tree_dir)
print(f" Exists after: {os.path.exists(tree_dir)}")
print(" Removed entire tree including all contents")
# Example 9: Error handling
print("\n9. Error Handling")
print("-" * 40)
# Try to remove non-existent file
try:
os.remove(os.path.join(test_dir, "nonexistent.txt"))
except FileNotFoundError:
print(" FileNotFoundError: File doesn't exist")
# Try to remove directory with remove()
test_subdir = os.path.join(test_dir, "subdir")
os.mkdir(test_subdir)
try:
os.remove(test_subdir)
except OSError:
print(" OSError: Cannot use remove() on directory")
os.rmdir(test_subdir)
# Example 10: Safe removal function
print("\n10. Comprehensive Safe Removal Function")
print("-" * 40)
def safe_remove(path):
"""Safely remove file or empty directory"""
try:
if not os.path.exists(path):
print(f" Path doesn't exist: {path}")
return False
if os.path.isfile(path):
os.remove(path)
print(f" Removed file: {os.path.basename(path)}")
return True
elif os.path.isdir(path):
if not os.listdir(path):
os.rmdir(path)
print(f" Removed empty directory: {os.path.basename(path)}")
return True
else:
print(f" Directory not empty: {os.path.basename(path)}")
return False
except Exception as e:
print(f" Error removing {path}: {e}")
return False
# Test safe_remove
test_file = os.path.join(test_dir, "safe_test.txt")
with open(test_file, 'w') as f:
f.write("test")
safe_remove(test_file)
test_empty_dir = os.path.join(test_dir, "empty")
os.mkdir(test_empty_dir)
safe_remove(test_empty_dir)
safe_remove(non_empty_dir) # Non-empty from earlier
shutil.rmtree(non_empty_dir)
# Cleanup
shutil.rmtree(test_dir)
print("\n" + "=" * 60)
print("Key Points:")
print(" - os.remove() deletes files")
print(" - os.rmdir() deletes empty directories")
print(" - shutil.rmtree() deletes directory trees")
print(" - Always check existence before removing")
print(" - Handle exceptions appropriately")
print("=" * 60)