Maintenance

Site is under maintenance — quizzes are still available.

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

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

15 matches
Sponsored Reserved space — layout preview until AdSense is connected
Files & data easy

Audit File Permissions Across a Project in Python

Walks through every file and directory in a project tree and prints POSIX permissions plus owner UID.

file permissions os.walk audit
Python
import os
import stat
from pathlib import Path

def audit_file_permissions(project_root):
    """Walk through project_root and print path, owner, and permissions for every file."""
    results = []
    for root, dirs, files in os.walk(project_root):
        for name in files + dirs:
            full_path = os.path.joi…
3 0 Open
Files & data easy

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.

filesystem cleanup pathlib
Python
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:
       …
5 0 Open
Files & data easy

Compare Two Folder Structures and Find Differences in Python

Walks two directories using os.walk, builds sets of relative paths, and prints items that exist in only one folder.

filesystem os.walk comparison
Python
import os

def compare_folders(path1, path2):
    """
    Compare the file/folder structure of two directories and print differences.
    """
    def get_structure(root):
        structure = set()
        for dirpath, dirnames, filenames in os.walk(root):
            rel_path = os.path.relpath(dirpath, root)
         …
4 0 Open
Files & data medium

Create a Local File Versioning System Using Pure Python

Track file changes locally by copying versions with SHA-256 hashes and JSON metadata using only the Python standard library.

file-versioning files backup
Python
import os
import shutil
import hashlib
import json
import time
from pathlib import Path

class LocalFileVersioning:
    def __init__(self, target_dir="versioned_files", versions_dir="versions"):
        self.target_dir = Path(target_dir)
        self.versions_dir = Path(versions_dir)
        self.metadata_file = self.…
3 0 Open
Files & data medium

Generate a Beautiful Folder Tree Visualization in Python

A Python utility that creates a visual tree of a directory structure, excluding common files, with configurable depth.

folder tree directory visualization
Python
import os
from pathlib import Path

class FolderTree:
    def __init__(self, root_path=".", ignore_list=None, max_depth=3):
        self.root = Path(root_path)
        self.ignore = set(ignore_list or [".git", "__pycache__", ".DS_Store"])
        self.max_depth = max_depth
        
    def generate(self):
        tree…
3 0 Open
Files & data medium

How to Generate an Inventory Report of All Files in Python

Walk a directory tree, collect metadata for every file, and write a CSV inventory report using Python's os, pathlib, and csv modules.

os.walk pathlib csv
Python
import os
import csv
from pathlib import Path
from datetime import datetime

def generate_inventory_report(root_dir: str = "/", output_file: str = "inventory_report.csv"):
    headers = ["File Path", "Size (bytes)", "Last Modified", "File Type"]
    rows = []
    start_time = datetime.now()
    
    for dirpath, dirna…
4 0 Open
Files & data medium

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.

sync backup filesystem
Python
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…
3 0 Open
Automation & scripting medium

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.

temporary-files cleanup automation
Python
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"),
  …
2 0 Open
Automation & scripting easy

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.

hardware inventory psutil
Python
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…
2 0 Open
Automation & scripting easy

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.

psutil automation monitoring
Python
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…
3 0 Open
Automation & scripting medium

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.

linux system-monitoring terminal
Python
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…
2 0 Open
Automation & scripting medium

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.

linux process monitoring
Python
#!/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…
2 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 medium

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.

psutil memory monitoring
Python
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…
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…
2 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.