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

Medium snippets you can copy, study, and run in the browser editor.

10 matches
Sponsored Reserved space — layout preview until AdSense is connected
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.…
4 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…
5 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 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…
3 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.