Python Delete Files
Learn to safely delete files and folders in Python!
๐๏ธ Let's Clean Up!
Sometimes you need to delete files and folders to clean up your computer or remove temporary files. Python makes it safe and easy to delete what you don't need anymore!
import os
# Delete a single file safely
if os.path.exists('old_file.txt'):
os.remove('old_file.txt')
print('โ
File deleted!')
else:
print('โ File not found!')
4 Ways to Delete Files and Folders
os.remove()
Delete a single file
os.rmdir()
Delete empty folder
shutil.rmtree()
Delete folder with everything inside
pathlib.unlink()
Modern way to delete files
Step 1: Delete Single Files
# Let's create some test files to practice deleting
test_files = ['test1.txt', 'test2.txt', 'test3.txt']
for filename in test_files:
with open(filename, 'w') as file:
file.write(f'This is {filename}')
print(f'โ
Created: {filename}')
print("Ready to practice deleting!")
import os
# Delete a single file
filename = 'test1.txt'
os.remove(filename)
print(f"โ
Deleted: {filename}")
# Check if it's really gone
if os.path.exists(filename):
print("โ File still exists!")
else:
print("โ
File successfully deleted!")
# Safe way - check if file exists first
filename = 'test2.txt'
if os.path.exists(filename):
os.remove(filename)
print(f"โ
Successfully deleted: {filename}")
else:
print(f"โ ๏ธ File not found: {filename}")
# Try to delete a file that doesn't exist
if os.path.exists('nonexistent.txt'):
os.remove('nonexistent.txt')
print("Deleted nonexistent file")
else:
print("โ
Smart! We didn't try to delete a file that doesn't exist")
Why check if file exists?
If you try to delete a file that doesn't exist, Python will give you an error and your program might crash. Always check first!
Step 2: Handle Errors Like a Pro
def safe_delete_file(filename):
"""Safely delete a file with error handling"""
try:
os.remove(filename)
print(f"โ
Successfully deleted: {filename}")
return True
except FileNotFoundError:
print(f"โ ๏ธ File not found: {filename}")
return False
except PermissionError:
print(f"โ Permission denied: Can't delete {filename}")
return False
except Exception as error:
print(f"โ Unexpected error: {error}")
return False
# Test our safe function
safe_delete_file('test3.txt') # Should work
safe_delete_file('missing.txt') # Should handle error nicely
safe_delete_file('C:\\Windows\\system32\\important.dll') # Permission denied
Common Deletion Errors:
- FileNotFoundError - File doesn't exist
- PermissionError - Not allowed to delete the file
- OSError - File is being used by another program
Step 3: Delete Folders
import os
import shutil
# Create some test folders
os.makedirs('empty_folder', exist_ok=True)
os.makedirs('full_folder', exist_ok=True)
# Put a file in the full folder
with open('full_folder/test_file.txt', 'w') as file:
file.write('This folder is not empty!')
print("โ
Test folders created!")
print("๐ empty_folder (empty)")
print("๐ full_folder (contains test_file.txt)")
# Delete empty folder with os.rmdir()
try:
os.rmdir('empty_folder')
print("โ
Empty folder deleted successfully!")
except OSError as e:
print(f"โ Could not delete folder: {e}")
# Try to delete folder with files (this will fail)
try:
os.rmdir('full_folder')
print("โ
Full folder deleted")
except OSError as e:
print(f"โ Cannot delete full folder with os.rmdir(): {e}")
print("๐ก Use shutil.rmtree() for folders with content!")
# Delete folder with all its contents using shutil.rmtree()
try:
shutil.rmtree('full_folder')
print("โ
Full folder and all contents deleted!")
except OSError as e:
print(f"โ Error deleting folder: {e}")
# Check if it's really gone
if os.path.exists('full_folder'):
print("โ Folder still exists!")
else:
print("โ
Folder completely removed!")
โ ๏ธ Be Careful with shutil.rmtree()
This command deletes EVERYTHING in the folder. Once it's gone, it's gone forever! Always double-check the folder name.
Step 4: Modern Way with pathlib
from pathlib import Path
# Create a test file using pathlib
modern_file = Path('modern_test.txt')
modern_file.write_text('This is a modern file!')
print(f"โ
Created: {modern_file}")
# Delete using pathlib
if modern_file.exists():
modern_file.unlink()
print(f"โ
Deleted using pathlib: {modern_file}")
# Modern way with error handling (Python 3.8+)
another_file = Path('maybe_exists.txt')
another_file.unlink(missing_ok=True) # Won't crash if file doesn't exist
print("โ
Attempted deletion (no error if file missing)")
# Create and delete directory
modern_dir = Path('modern_directory')
modern_dir.mkdir(exist_ok=True)
print(f"โ
Created directory: {modern_dir}")
modern_dir.rmdir() # Only works for empty directories
print(f"โ
Deleted empty directory: {modern_dir}")
Why pathlib is awesome:
- โจ More readable and intuitive
- ๐ก๏ธ Built-in safety features
- ๐ Works the same on Windows, Mac, and Linux
- ๐ง Many helpful methods built-in
๐ฏ Practical Examples
import os
def cleanup_temp_files():
"""Clean up temporary files in current directory"""
temp_extensions = ['.tmp', '.temp', '.log', '.cache']
deleted_count = 0
print("๐งน Cleaning up temporary files...")
# Look at all files in current directory
for filename in os.listdir('.'):
# Check if it's a file (not a directory)
if os.path.isfile(filename):
# Check if it has a temporary extension
for ext in temp_extensions:
if filename.endswith(ext):
try:
os.remove(filename)
print(f" โ
Deleted: {filename}")
deleted_count += 1
except Exception as e:
print(f" โ Could not delete {filename}: {e}")
break
print(f"๐ Cleanup complete! Deleted {deleted_count} temporary files.")
# Create some temporary files for testing
test_temp_files = ['test.tmp', 'cache.cache', 'debug.log', 'temp.temp']
for temp_file in test_temp_files:
with open(temp_file, 'w') as f:
f.write('temporary content')
print("Created temporary files for testing")
# Run the cleanup
cleanup_temp_files()
import shutil
def backup_and_delete(filename):
"""Make a backup before deleting a file"""
if not os.path.exists(filename):
print(f"โ File not found: {filename}")
return False
# Create backup folder
backup_folder = 'backups'
os.makedirs(backup_folder, exist_ok=True)
# Create backup filename
backup_name = f"{filename}.backup"
backup_path = os.path.join(backup_folder, backup_name)
try:
# Copy file to backup
shutil.copy2(filename, backup_path)
print(f"โ
Backup created: {backup_path}")
# Delete original file
os.remove(filename)
print(f"โ
Original file deleted: {filename}")
return True
except Exception as e:
print(f"โ Error during backup and delete: {e}")
return False
# Test the backup and delete function
test_file = 'important_data.txt'
with open(test_file, 'w') as f:
f.write('This is important data that should be backed up!')
backup_and_delete(test_file)
def confirm_delete(filename):
"""Ask user for confirmation before deleting"""
if not os.path.exists(filename):
print(f"โ File not found: {filename}")
return False
# Show file info
file_size = os.path.getsize(filename)
print(f"๐ File: {filename}")
print(f"๐ Size: {file_size} bytes")
# Ask for confirmation
response = input(f"Are you sure you want to delete '{filename}'? (yes/no): ")
if response.lower() in ['yes', 'y']:
try:
os.remove(filename)
print(f"โ
File deleted: {filename}")
return True
except Exception as e:
print(f"โ Error deleting file: {e}")
return False
else:
print("โ Deletion cancelled by user")
return False
# Create a test file
test_file = 'ask_before_delete.txt'
with open(test_file, 'w') as f:
f.write('This file requires confirmation to delete')
# Test the confirmation function
# confirm_delete(test_file) # Uncomment to test interactively
print("๐ก Uncomment the line above to test interactive deletion")
Advanced: Clean Up Old Files
import time
from datetime import datetime, timedelta
def delete_old_files(folder_path='.', days_old=7):
"""Delete files older than specified number of days"""
print(f"๐๏ธ Looking for files older than {days_old} days in '{folder_path}'")
# Calculate cutoff time
cutoff_time = time.time() - (days_old * 24 * 60 * 60)
deleted_count = 0
try:
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
# Skip directories
if os.path.isdir(file_path):
continue
# Get file modification time
file_time = os.path.getmtime(file_path)
# Check if file is old enough
if file_time < cutoff_time:
try:
# Convert timestamp to readable date
file_date = datetime.fromtimestamp(file_time)
os.remove(file_path)
print(f" โ
Deleted old file: {filename} (from {file_date.strftime('%Y-%m-%d')})")
deleted_count += 1
except Exception as e:
print(f" โ Could not delete {filename}: {e}")
print(f"๐ Cleanup complete! Deleted {deleted_count} old files.")
except Exception as e:
print(f"โ Error scanning directory: {e}")
# Create some test files with different ages (simulate old files)
import time
test_files = ['old_file1.txt', 'old_file2.txt', 'new_file.txt']
for i, filename in enumerate(test_files):
with open(filename, 'w') as f:
f.write(f'Content of {filename}')
# Make first two files appear older by changing their timestamp
if i < 2:
# Set timestamp to 10 days ago
old_time = time.time() - (10 * 24 * 60 * 60)
os.utime(filename, (old_time, old_time))
print("Created test files with different ages")
# Clean up files older than 5 days
delete_old_files('.', days_old=5)
๐ Quick Reference
Delete File
os.remove('file.txt')
Delete single file
Delete Empty Folder
os.rmdir('folder')
Delete empty directory
Delete Full Folder
shutil.rmtree('folder')
Delete directory with contents
Modern Way
Path('file.txt').unlink()
Delete with pathlib
๐ก๏ธ Safety Tips
Always Follow These Rules:
- โ Check if file exists before deleting
- โ Use try/except to handle errors
- โ Make backups of important files
- โ Ask for confirmation before deleting
- โ Test with dummy files first
- โ Never delete system files
- โ Don't delete files you didn't create