Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected
Reference library

Automation & scripting

CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.

12 matches
Sponsored Reserved space — layout preview until AdSense is connected
Automation & scripting medium

Automatically Download the Latest Software Release from GitHub with Python

Use the GitHub API to fetch the latest release metadata and download the first asset (binary or archive) to a local directory.

github api download
Python
import requests
import sys
from pathlib import Path

def download_latest_release(owner: str, repo: str, output_dir: str = ".") -> None:
    """Download the latest release asset from a GitHub repository."""
    url = f"https://api.github.com/repos/{owner}/{repo}/releases/latest"
    response = requests.get(url)
    res…
2 0 Open
Automation & scripting easy

Create a Simple HTTP File Server in Python

This code creates a simple HTTP file server that serves files from the current working directory on port 8000 using Python's built-in http.server module.

http server file-server
Python
import http.server
import socketserver
import os

PORT = 8000
DIRECTORY = os.getcwd()

class CustomHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

    def log_message(self, format, *args):
        print(f"[{self.log…
3 0 Open
Automation & scripting medium

Detect Circular Imports Across Python Projects Automatically

This script walks through all .py files in a directory, builds an import graph, and uses depth-first search to find cycles—printing each circular dependency chain.

circular-imports import-graph ast
Python
import ast
import sys
from pathlib import Path
from collections import defaultdict, deque

def find_imports(filepath):
    """Return set of module names imported by a Python file."""
    imports = set()
    try:
        with open(filepath) as f:
            tree = ast.parse(f.read())
    except (SyntaxError, UnicodeDe…
2 0 Open
Automation & scripting medium

Detect and Remove Blurry Images in Python with OpenCV

Automatically scan a directory of images, detect blur using Laplacian variance, and remove blurry images with a dry-run option for safety.

opencv image-processing automation
Python
from pathlib import Path
import cv2
import numpy as np

def is_blurry(image_path, threshold=100.0):
    """
    Detect if an image is blurry using Laplacian variance.
    Returns True if blurry, False otherwise.
    """
    img = cv2.imread(str(image_path), cv2.IMREAD_GRAYSCALE)
    if img is None:
        return True…
6 0 Open
Automation & scripting medium

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.

orphan files file cleanup automation
Python
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'…
4 0 Open
Automation & scripting medium

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.

deduplication files hashing
Python
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…
5 0 Open
Automation & scripting medium

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.

file-system disk-space pathlib
Python
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:
      …
4 0 Open
Automation & scripting easy

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.

compression zipfile file-archiving
Python
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
    "…
2 0 Open
Automation & scripting medium

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.

code metrics lines of code cyclomatic complexity
Python
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()…
4 0 Open
Automation & scripting medium

How to Generate a Dependency Graph for Python Projects

This script walks through a Python project directory, parses each .py file's imports, and prints a dependency graph showing which modules depend on which other modules.

ast dependency graph import parsing
Python
import os
import ast
from pathlib import Path
from collections import defaultdict

def get_imports(filepath):
    with open(filepath) as f:
        try:
            tree = ast.parse(f.read())
        except SyntaxError:
            return []
    imports = []
    for node in ast.walk(tree):
        if isinstance(node, …
2 0 Open
Automation & scripting easy

How to Recover Deleted .txt Files from a Backup in Python

A Python function that searches a backup directory recursively and copies all .txt files to a destination folder, printing each recovered file name and a total count.

backup recovery file-operations
Python
import os
import shutil
from pathlib import Path

def recover_deleted_txt_files(source_backup_dir: str, destination_dir: str) -> None:
    """Recover .txt files from backup directory."""
    backup_path = Path(source_backup_dir)
    dest_path = Path(destination_dir)
    dest_path.mkdir(parents=True, exist_ok=True)

  …
2 0 Open
Automation & scripting medium

How to check Python files for common coding mistakes

Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.

ast linting code-quality
Python
import ast
import os
import sys

def check_file(filepath):
    try:
        with open(filepath) as f:
            code = f.read()
        tree = ast.parse(code, filename=filepath)
    except SyntaxError as e:
        print(f"{filepath}: SyntaxError: {e.msg}")
        return
    
    issues = []
    for node in ast.wal…
3 0 Open

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.