Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Split Strings in Python (Beginner-Friendly)
Split Python strings by a delimiter into lists, plus a cleanup variant that strips whitespace and filters empty parts.
def split_text(text, delimiter=" "):
"""Split a string by a delimiter and return a list of parts."""
return text.split(delimiter)
def split_text_with_cleanup(text, delimiter=" "):
"""Split a string, stripping whitespace and filtering empty parts."""
parts = text.split(delimiter)
cleaned = [part.s…
Build a Python Script That Detects and Deletes Empty Files Across Folders
A Python script that recursively finds and removes all zero-byte files across nested directories, returning a list of deleted paths.
import os
from pathlib import Path
def find_and_delete_empty_files(root_dir: str) -> list:
"""Find and delete all empty files under root_dir. Returns list of deleted paths."""
deleted = []
for file_path in Path(root_dir).rglob('*'):
if file_path.is_file() and file_path.stat().st_size == 0:
…
How to Prune Empty Directories in Python with os.walk
Remove all empty subdirectories bottom-up using os.walk with topdown=False and os.rmdir, safely ignoring non-empty folders.
import os
def prune_empty_dirs(root):
"""Remove all empty subdirectories under root, bottom-up."""
for dirpath, dirnames, filenames in os.walk(root, topdown=False):
if dirpath == root:
continue
try:
os.rmdir(dirpath)
print(f"Removed: {dirpath}")
exce…
How to Close a Generator and Handle GeneratorExit in Python
This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.
def countdown(n):
try:
while n > 0:
yield n
n -= 1
finally:
print(f"Generator closed after countdown completed")
if __name__ == "__main__":
gen = countdown(5)
print(next(gen))
print(next(gen))
gen.close()
print("Generator closed explicitly")
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 Filter Git History to Remove Secret File Entries in Python
A pure-Python mock that filters a repository's history to drop any commit that touched a secret file, so you can plan a cleanup before rewriting Git history.
from pathlib import Path
import json
def filter_history(history, secret_path):
"""Remove entries that touch the secret file."""
return [entry for entry in history if secret_path not in entry["files"]]
if __name__ == "__main__":
repo_history = [
{"commit": "a1b2c3", "message": "Add app", "files": …
How to Cancel an asyncio Task with Graceful Cleanup in Python
Cancel a running asyncio task, handle the cancellation signal inside a worker coroutine to perform cleanup, then re-raise so the cancellation propagates correctly.
import asyncio
async def worker(name: str, sleep: float) -> None:
try:
print(f"{name}: starting")
await asyncio.sleep(sleep)
print(f"{name}: completed")
except asyncio.CancelledError:
print(f"{name}: cancelled, cleaning up...")
await asyncio.sleep(0.2) # Simulate clea…
How to Implement a Redis-Like Cache Dictionary in Python
Build a RedisMockDict class that mimics basic Redis key-value operations with TTL support, expiry cleanup, and standard dict-like methods.
from collections import OrderedDict
import time
class RedisMockDict:
def __init__(self, ttl=None):
self._data = OrderedDict()
self._ttl = ttl # default TTL in seconds, None = no expiry
self._expiry = {}
def set(self, key, value, ttl=None):
"""Set a key-value pair with optiona…
How to Drain a Connection Pool Before Exit in Python
Gracefully close all pooled sockets using a thread-safe ConnectionPool that drains connections before program exit.
import socket
import threading
import time
import random
class ConnectionPool:
def __init__(self, size=5):
self.pool = []
self.lock = threading.Lock()
self.closed = False
for _ in range(size):
self.pool.append(self.create_connection())
def create_connection(sel…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
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.