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
Delete Methods
Safe
Operations
Easy
To Learn

4 Ways to Delete Files and Folders

๐Ÿ“„

os.remove()

Delete a single file

Files only Simple
๐Ÿ“

os.rmdir()

Delete empty folder

Empty folders Safe
๐ŸŒณ

shutil.rmtree()

Delete folder with everything inside

Full folders Powerful
๐Ÿ”—

pathlib.unlink()

Modern way to delete files

Modern Easy

Step 1: Delete Single Files

Create Test Files First

# 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!")
Method 1: Basic File Deletion

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!")
Method 2: Safe Deletion (Recommended)

# 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

Super Safe Deletion Function

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

Create Test 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

# 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 Everything Inside

# 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

The Cool Modern Way

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

Clean Up Temporary Files

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()
Safe Backup and Delete

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)
Ask Before Deleting

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

Delete Files Older Than X Days

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

๐Ÿง  Quick Quiz

Which function deletes a single file?

What happens when you try to delete a non-empty directory with os.rmdir()?

Which method should you use to delete a directory with all its contents?