Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Find Sensitive Information in Log Files with Python
Scan log files for emails, IP addresses, API keys, and passwords using regular expressions in Python.
import re
import os
from pathlib import Path
def find_sensitive_info(log_path):
"""Scans log files for patterns like emails, IPs, API keys, and passwords."""
patterns = {
'Email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
'IP Address': r'\b(?:\d{1,3}\.){3}\d{1,3}\b',
'API Key'…
Find Unused Python Packages Automatically
Scan a Python project's source files for imports and list installed packages not imported anywhere.
import pkg_resources
import ast
import os
import sys
from pathlib import Path
def find_imports_in_project(project_dir="."):
imports = set()
for py_file in Path(project_dir).rglob("*.py"):
try:
with open(py_file, "r") as f:
tree = ast.parse(f.read())
for node in …
Find and Delete Duplicate Files Using Hashing in Python
Walk a directory tree, compute SHA256 hashes for every file, and delete duplicates that share the same hash.
import hashlib
import os
from pathlib import Path
def file_hash(path, block_size=65536):
"""Return SHA256 hash of file content."""
hasher = hashlib.sha256()
with open(path, 'rb') as f:
while chunk := f.read(block_size):
hasher.update(chunk)
return hasher.hexdigest()
def find_and_d…
Find the Largest Files Consuming Disk Space with a Beautiful Terminal Report in Python
Scan a directory recursively and print a formatted terminal report of the largest files, with human-readable sizes.
import os
import sys
from pathlib import Path
def get_largest_files(directory: str, count: int = 10) -> list:
"""
Scan the given directory and return the largest files.
Args:
directory: Path to the directory to scan
count: Number of largest files to return
Returns:
…
Generate Beautiful Project Documentation from Python Source Code Automatically
Automatically generate a markdown summary of function docstrings from any Python source file using the AST module.
import ast
import inspect
from pathlib import Path
def extract_docstrings_from_file(filepath):
"""Parse a Python file and collect function docstrings."""
source = Path(filepath).read_text()
tree = ast.parse(source)
docs = []
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef…
Generate Holiday Calendars for Different Countries in Python
Generate a sorted list of public holidays for a given country and year using Python's calendar and datetime modules.
import calendar
from datetime import date, timedelta
def generate_holiday_calendar(country_code, year=2025):
holidays = []
if country_code == "US":
# New Year's Day
holidays.append(date(year, 1, 1))
# Independence Day
holidays.append(date(year, 7, 4))
# Thanksgivin…
Generate Strong Random Passwords with Custom Rules in Python
Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.
import secrets
import string
def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
pool = ''
if use_lower:
pool += string.ascii_lowercase
if use_upper:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_pu…
Generate Strong SSH Keys and Save Them Securely with Python
Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.
import os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
"""Generate a 4096-…
How to Automatically Download Every Favicon from a List of Websites in Python
Download each website's favicon.ico file by constructing its URL, making a GET request, and saving the binary content locally.
import requests
from urllib.parse import urlparse
import os
websites = [
"https://www.google.com",
"https://www.github.com",
"https://www.stackoverflow.com"
]
def download_favicon(url):
parsed = urlparse(url)
favicon_url = f"{parsed.scheme}://{parsed.netloc}/favicon.ico"
response = requests.g…
How to Build a Cryptocurrency Price Tracker in Python
A continuous Python script that fetches real-time cryptocurrency prices from the CoinGecko API and displays them on a loop.
import requests
import time
def get_crypto_prices(coin_ids=["bitcoin", "ethereum", "solana"]):
url = "https://api.coingecko.com/api/v3/simple/price"
params = {
"ids": ",".join(coin_ids),
"vs_currencies": "usd"
}
try:
response = requests.get(url, params=params, timeout=10)
…
How to Build a Python Tool That Finds Trending Open Source Projects Daily
A Python script that queries the GitHub Search API to fetch the top 5 trending repositories created in the last day, sorted by stars, with optional language filtering.
import requests
import json
import datetime
def fetch_trending_projects(language: str = "", since: str = "daily"):
url = "https://api.github.com/search/repositories"
date_limit = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
query = f"created:>{date_limit} language:{language}" if langua…
How to Compare Two GitHub Repositories and Highlight Differences in Python
Fetch metadata from two GitHub repositories using the GitHub API and compare key attributes like stars, forks, license, and language, printing any differences.
import requests
import json
from pathlib import Path
def fetch_repo_data(owner, repo_name):
"""Fetch repository metadata from GitHub API."""
url = f"https://api.github.com/repos/{owner}/{repo_name}"
response = requests.get(url)
response.raise_for_status()
return response.json()
def compare_repos(…
How to Compress a Folder in Python While Preserving Directory Structure
A Python function that uses zipfile to recursively compress a folder, maintaining the original directory hierarchy inside the zip archive.
import os
import zipfile
from pathlib import Path
def compress_folder(source_dir: str, output_zip: str):
"""
Compress a folder into a zip file, preserving the directory structure.
Args:
source_dir: Path to the source directory to compress
output_zip: Path for the output zip file
"…
How to Create a File Organizer That Sorts Files Automatically in Python
A Python script that scans a given folder, categorizes files by extension (Images, Documents, Audio, Video, Archives, Misc), and moves them into subfolders automatically.
import os
import shutil
from pathlib import Path
FILE_CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp"],
"Documents": [".pdf", ".docx", ".txt", ".csv", ".xlsx"],
"Audio": [".mp3", ".wav", ".flac", ".aac"],
"Video": [".mp4", ".mkv", ".avi", ".mov"],
"Archives": [".zip", ".tar", ".g…
How to Detect Network Interface Changes in Python
Monitor active network interfaces and print a message when an interface is added or removed using psutil and socket.
import socket
import psutil
import time
def get_network_interfaces():
"""Return a set of currently active interface names."""
active_ifaces = set()
for iface, addrs in psutil.net_if_addrs().items():
for addr in addrs:
if addr.family == socket.AF_INET: # IPv4 address present
…
How to Detect Recently Installed Software in Python
Uses subprocess to call pip and parse package metadata to list recently installed Python packages.
import subprocess
import sys
from datetime import datetime, timedelta
def detect_recently_installed(days=7):
"""Detect recently installed software packages."""
recent_packages = []
cutoff_date = datetime.now() - timedelta(days=days)
try:
# For pip-installed packages (Python packages)
…
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 Download All Assets from GitHub Releases in Python
Downloads every asset attached to the latest GitHub release of a repository, saving them locally using the GitHub API and Python's requests and pathlib libraries.
import requests
import os
import zipfile
from pathlib import Path
def download_github_release_assets(owner: str, repo: str, output_dir: str = "release_assets") -> None:
"""Downloads all assets from the latest release of a GitHub repository."""
releases_url = f"https://api.github.com/repos/{owner}/{repo}/relea…
How to Download a GitHub Repository as a ZIP File in Python
Download any public GitHub repository as a ZIP file using the GitHub API and Python's requests and zipfile modules.
import requests
import zipfile
import io
import os
def download_github_repo_as_zip(repo_url, output_path='.'):
"""
Download a GitHub repository as a ZIP file.
Args:
repo_url (str): Full GitHub repository URL (e.g., 'https://github.com/username/repo')
output_path (str): Directory to sa…
How to Find Stale GitHub Issues in Python
Filter a list of GitHub issues to find those not updated within a configurable number of days using Python datetime arithmetic.
import os
from datetime import datetime, timezone, timedelta
import re
# Simulated GitHub issue data structure
SAMPLE_ISSUES = [
{"number": 101, "title": "Login button not working", "updated_at": "2025-06-01T12:00:00Z", "assignee": "alice"},
{"number": 102, "title": "Fix database migration error", "updated_at…
How to Generate Project Statistics Including Lines of Code and Complexity in Python
Walk through a Python script that scans a project directory for Python files, counts lines of code excluding blanks and comments, and estimates cyclomatic complexity by counting decision keywords.
import os
from pathlib import Path
def count_lines_of_code(filepath):
"""Counts lines of code in a Python file, excluding blank lines and comments."""
try:
with open(filepath, 'r') as f:
lines = f.readlines()
code_lines = [line for line in lines if line.strip() and not line.strip()…
How to Generate a QR Code in Python
Generate a QR code image from a URL string using the qrcode library and save it as a PNG file.
import qrcode
# Data to encode
data = "https://www.example.com"
# Create QR code instance
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# Add data to QR code
qr.add_data(data)
qr.make(fit=True)
# Create an image from the QR code
img = qr.…
How to Monitor Domain Expiration Dates in Python
A Python script that checks domain expiration dates using the python-whois library and warns when a domain is expiring soon.
import whois
from datetime import datetime, timedelta
import time
def check_domain_expiry(domain_name):
"""Check when a domain expires and warn if soon."""
try:
w = whois.whois(domain_name)
expiry = w.expiration_date
# Handle list or single date
if isinstance(expiry, list):
…
How to Monitor Laptop Battery Health Over Time in Python
Log battery percentage, power status, and remaining time every N seconds to a JSON file using psutil for ongoing health monitoring.
import time
import json
from pathlib import Path
from datetime import datetime
try:
import psutil
except ImportError:
print("psutil required: pip install psutil")
exit(1)
LOG_FILE = Path("battery_health_log.json")
def monitor_battery(log_interval=60, duration=300):
"""Log battery percentage and rema…
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.