Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Automatically Clean Temporary Files from Applications Using Python
A Python script that safely deletes temporary files from common application temp directories across Windows, Linux, and macOS, tracking cleaned count and disk space.
import os
import shutil
import tempfile
import platform
def clean_application_temp_files():
"""Delete common temporary file locations safely."""
system = platform.system()
temp_dirs = []
if system == "Windows":
temp_dirs.extend([
os.path.join(os.getenv("LOCALAPPDATA"), "Temp"),
…
Detect Memory Leaks in Python with Weak References
A custom LeakDetector uses weak references and garbage collection to find class instances that survive past expected cleanup in long-running Python applications.
import gc
import sys
import weakref
import time
from collections import defaultdict
class LeakDetector:
def __init__(self):
self._tracked = defaultdict(list)
def track_class(self, cls):
"""Track all instances of a class for leak detection."""
old_init = cls.__init__
def new_in…
Find Orphan Files Not Referenced Anywhere in Python
Scan a project directory for files whose names never appear in the content of other files, identifying potentially unused resources.
import os
from pathlib import Path
import re
def find_orphan_files(root_dir: str, extensions: set = None, ignore_patterns: list = None):
"""Find files not referenced by any other file in the project."""
if extensions is None:
extensions = {'.txt', '.md', '.py', '.html', '.css', '.js', '.json', '.yaml'…
How to Clean Old Temp Files in Python
A Python script that scans a directory and deletes files older than a configurable age (default: one week), with safe error handling.
import os
import time
from pathlib import Path
def clean_old_temp_files(directory=".", max_age_seconds=7 * 24 * 60 * 60):
"""
Remove files in directory older than the specified age.
Args:
directory: Path to directory to clean
max_age_seconds: Maximum age in seconds (default: 1 week)
…
How to Detect Unused Images in a Project with Python
A Python script that scans a website project folder, identifies all image files, and checks HTML/CSS/JS files to find which images are never referenced.
import os
import re
from pathlib import Path
def find_unused_images(project_path):
image_exts = {'.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp'}
used_images = set()
all_images = set()
# Find all image files
for root, _, files in os.walk(project_path):
for file in files:
…
How to Filter Docker Containers for Pruning in Python
Simulate Docker's container prune by filtering a JSON list for exited containers older than a cutoff, returning pruned IDs and space freed.
import json
from datetime import datetime, timedelta
def parse_docker_ps(json_output: str, older_than_hours: int = 24) -> list:
containers = json.loads(json_output)
cutoff = datetime.now() - timedelta(hours=older_than_hours)
return [
c for c in containers
if datetime.fromisoformat(c["crea…
How to Hash Duplicate Photos and Delete Copies in Python
This script hashes image files in a directory using SHA-256 and deletes duplicate copies while keeping the first occurrence, ideal for cleaning up photo libraries.
from pathlib import Path
import hashlib
def file_hash(path, chunk_size=8192):
hasher = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
hasher.update(chunk)
return hasher.hexdigest()
def delete_duplicate_photos(directory):
directory …
How to Scan Files Against a Malware Hash List in Python
Compare a file's SHA-256 hash against a known malware hash set and report whether it's clean or infected.
import hashlib
from pathlib import Path
# Mock file content (in real usage, read from disk)
MOCK_FILE_CONTENT = b"print('hello world')"
KNOWN_MALWARE_HASHES = {
"8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
"5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
}
def sha25…
Post a message to a Slack webhook in Python
Send a message to a Slack webhook endpoint using the standard library's urllib.request, handling the POST request and response cleanly.
import json
from urllib import request
def post_to_slack(webhook_url: str, message: str) -> dict:
payload = json.dumps({"text": message}).encode("utf-8")
req = request.Request(
webhook_url,
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
wit…
Browse by section
Each section groups closely related Python snippets.
Automation & scripting — Python code examples
What you will find here
This page collects automation & scripting snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.