Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Split Files by Extension in Python
Group files in a folder by their file extension into a dictionary using pathlib.
from pathlib import Path
def split_files_by_extension(folder_path):
folder = Path(folder_path)
files_by_ext = {}
for file_path in folder.iterdir():
if file_path.is_file():
ext = file_path.suffix.lower() or "no_extension"
files_by_ext.setdefault(ext, []).append(file_path.na…
How to Sync Two Folders in Python (Lightweight Backup)
A Python script that synchronizes a source folder to a destination folder, copying new or updated files and removing files that no longer exist in the source.
import os
import shutil
import sys
from pathlib import Path
def sync_folders(src: Path, dst: Path):
"""Sync src folder to dst folder, copying missing/updated files."""
dst.mkdir(parents=True, exist_ok=True)
for src_path in src.rglob("*"):
relative = src_path.relative_to(src)
dst_path = ds…
How to Walk a Directory Tree with os.walk in Python
A generator function that recursively walks a directory tree and yields every file path found using the os.walk generator.
import os
def walk_directory_tree(root_path: str):
"""Walk a directory tree and yield file paths using os.walk generator."""
for dirpath, dirnames, filenames in os.walk(root_path):
for filename in filenames:
yield os.path.join(dirpath, filename)
if __name__ == "__main__":
# Create a…
How to resolve a symlink to its real path in Python with pathlib
Use Path.resolve() to turn a symlink path into its absolute target path, handling relative symlinks and eliminating symbolic links.
from pathlib import Path
def resolve_symlink(path):
p = Path(path)
return str(p.resolve())
if __name__ == "__main__":
# Create a symlink to demonstrate the resolution
target = Path("/tmp/real_target.txt")
target.write_text("hello")
link = Path("/tmp/my_link.txt")
try:
link.symlink…
How to implement a Facade class to simplify subsystem calls in Python
Use a Facade class to wrap complex subsystem interactions behind a simple start() method, hiding the details and providing a clean interface.
class CPU:
def freeze(self):
print("CPU: freezing")
def jump(self, position):
print(f"CPU: jumping to {position}")
def execute(self):
print("CPU: executing")
class Memory:
def load(self, position, data):
print(f"Memory: loading '{data}' at {position}")
class HardDr…
Python Adapter Class: Wrap Legacy Interface
Convert a legacy system's interface into a modern one using the Adapter pattern in Python, translating method calls and data formats.
class LegacySystem:
"""Legacy interface - old method names and parameter format."""
def query_employee_info(self, emp_id, emp_name):
return f"Legacy: {emp_id} - {emp_name}"
def update_employee_department(self, emp_id, department_code):
return f"Legacy: Updated {emp_id} to dept {department_…
Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo
This demo shows how to structure a function that explains its own reasoning step-by-step, mimicking chain-of-thought prompting for AI systems.
def solve_math_step_by_step(expression: str) -> str:
"""Solves a simple expression, showing each reasoning step."""
# Step 1: Parse the expression (assume "a + b" or "a - b")
parts = expression.split()
a = int(parts[0])
op = parts[1]
b = int(parts[2])
steps = []
steps.append(f"Step…
Demonstrate Prompt Injection Bypass in Python
Simulate why naive system prompt filters fail against prompt injection with casing and spacing variations.
# Demonstrate why system prompts can be bypassed by simulated user input
# This demo shows a naive filter being ignored via prompt injection
def process_user_message(message, system_rules):
"""Simulate an AI that follows system rules but gets tricked."""
# Claim to check system rules
for rule in system_ru…
How to Build a System-User-Assistant Message List in Python
Use dataclasses to model a chat conversation and build the system/user/assistant message list expected by LLM APIs.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Message:
role: str
content: str
@dataclass
class Conversation:
messages: List[Message] = field(default_factory=list)
def add_system(self, content: str) -> None:
self.messages.append(Message(role="system", con…
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"),
…
Automatically Generate Hardware Inventory Reports in Python
Generate a system hardware report including OS version, CPU cores, RAM, and disk usage using platform and psutil.
import platform
import psutil # requires: pip install psutil
from datetime import datetime
def generate_hardware_report():
report_lines = []
report_lines.append(f"Report Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report_lines.append(f"System: {platform.system()} {platform.release()} ({pl…
Automatically Log CPU, RAM, and Disk Usage Every Minute in Python
This script logs CPU, RAM, and disk usage to a CSV file every 60 seconds using psutil and Python's standard library.
import psutil
import time
import csv
from pathlib import Path
LOG_FILE = Path("system_usage_log.csv")
INTERVAL_SECONDS = 60
def log_system_usage():
"""Write CPU, RAM, and disk usage to CSV every minute."""
file_exists = LOG_FILE.exists()
with open(LOG_FILE, mode="a", newline="") as f:
writer = cs…
Build a Terminal Dashboard That Displays Real-Time System Performance in Python
A Python script that reads Linux system files to display a real-time terminal dashboard with CPU usage, memory usage, and CPU temperature.
import os, time, sys
from collections import deque
def get_cpu_temp():
try:
with open("/sys/class/thermal/thermal_zone0/temp") as f:
return round(int(f.read().strip()) / 1000, 1)
except:
return None
def get_mem_usage():
with open("/proc/meminfo") as f:
lines = f.readli…
Find Zombie Processes on Linux with Python
Parse the output of `ps -eo pid,stat,comm` to detect processes in zombie state (Z) on a Linux system and report their PIDs and commands.
#!/usr/bin/env python3
import os
import subprocess
def find_zombie_processes():
"""Find zombie processes (state 'Z') running on Linux."""
try:
result = subprocess.run(['ps', '-eo', 'pid,stat,comm'], capture_output=True, text=True, check=True)
zombies = []
for line in result.stdout.stri…
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:
…
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 Applications Consuming Excessive Memory in Python
Use psutil to list the top memory-using processes by RSS and print their names, PIDs, and memory usage in MB.
import psutil
def find_top_memory_processes(limit=5):
"""Return top `limit` processes by memory usage (RSS)."""
processes = []
for proc in psutil.process_iter(['pid', 'name', 'memory_info']):
try:
info = proc.info
mem = info['memory_info'].rss if info['memory_info'] else 0…
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.
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…
Mock systemctl Wrapper in Python for Service Testing
A Python class-based mock of systemctl that simulates start, stop, restart, and status operations for a service, useful for testing automation scripts.
import subprocess
import sys
class ServiceManager:
def __init__(self, service_name):
self.service_name = service_name
self.status = "inactive"
def start(self):
self.status = "active"
print(f"Starting {self.service_name}... OK")
def stop(self):
self.status …
Mount ISO Loop Device Mock Script in Python
Simulate ISO mounting with a loop device using a mock class — useful for testing scripts that depend on mount/unmount without actual system privileges.
import os
import tempfile
from dataclasses import dataclass
from pathlib import Path
@dataclass
class LoopDevice:
path: str
iso_path: str
mounted: bool = False
def mount(self, mount_point: str):
if self.mounted:
raise RuntimeError(f"Loop device {self.path} already mounted")
…
How to create a dated snapshot path for a dataset in Python
Generate a versioned directory path combining a base directory, dataset name, and today's date, ready for creating snapshots in data pipelines.
import datetime
import os
from pathlib import Path
def snapshot_path(base_dir: str, dataset_name: str) -> Path:
"""Return a dated snapshot path for a dataset under a base directory."""
today = datetime.date.today().isoformat()
return Path(base_dir) / dataset_name / today
if __name__ == "__main__":
…
Trigger a Pipeline When a New File Appears in a Directory
Poll a directory every 0.5 seconds and return the name of the first new file that appears, or None after a timeout.
import time
from pathlib import Path
def watch_for_file(directory: str, interval: float = 0.5, timeout: float = 10.0) -> str | None:
"""Poll a directory and trigger when a new file appears."""
watch_dir = Path(directory)
watch_dir.mkdir(exist_ok=True)
known_files = set(watch_dir.iterdir())
s…
How to Archive a Repository as a ZIP in Python
Create a ZIP archive of a repository directory with a mock export, skipping hidden files and __pycache__ folders.
import zipfile
import io
import os
from pathlib import Path
def archive_repo_mock(repo_path, output_path="repo_archive.zip"):
"""Create a zip archive of a repository directory (mock export)."""
repo = Path(repo_path)
if not repo.exists():
raise FileNotFoundError(f"Repository not found: {repo}")
…
How to Mock Git Worktree Creation in Python
Create a mock Git worktree setup with parallel branch directories and state files for testing or simulation.
import os
import tempfile
from pathlib import Path
def create_mock_worktree(base_dir: Path, branches: list[str]) -> dict[str, Path]:
"""
Mock Git worktree creation: creates parallel directories for each branch
under the base directory, simulating independent worktrees.
"""
worktrees = {}
for b…
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.