Reference library

Python Code Samples

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

7 matches
Files & data easy

How to Watch a Directory for New Files in Python

Poll a directory at regular intervals and detect newly added files, printing each one as it appears.

file watching polling os.listdir
Python
import time
import os
from pathlib import Path

WATCH_DIR = Path("watched_files")

def watch_for_new_files(directory: Path, sleep_time: float = 1.0, max_iterations: int = 10):
    """Poll a directory for new files and print when one appears."""
    directory.mkdir(exist_ok=True)
    existing = set(os.listdir(directory…
12 0 Open
Files & data medium

Tail last N lines of growing log file in Python

Prints the last n lines of a log file and follows new content appended to it, polling for size changes.

log-file file-handling polling
Python
import time
from pathlib import Path

def tail_log(file_path, n=10, poll_interval=1.0, timeout=10):
    """
    Print the last n lines and follow new lines appended to a growing log file.
    """
    path = Path(file_path)
    # Read the last n lines from the current file
    with path.open("r", encoding="utf-8") as f…
12 0 Open
Automation & scripting easy

How to Watch a Folder and Convert New Images in Python

Watch a folder for new files and mock-convert images by copying and renaming them in an output directory.

folder-watching automation pathlib
Python
import time
import hashlib
from pathlib import Path
from datetime import datetime

def mock_convert_image(source: Path, dest_dir: Path) -> Path:
    """Mock image conversion: copy bytes and add .converted suffix."""
    dest = dest_dir / f"{source.stem}.converted{source.suffix}"
    dest.write_bytes(source.read_bytes(…
12 0 Open
Data pipelines & processing easy

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.

polling filesystem file-watcher
Python
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…
13 0 Open
API design & gRPC easy

How to Poll an Operation Status Endpoint in Python

Mock a polling endpoint in Python that simulates checking an async operation's status until it completes or times out.

polling api async
Python
import time
import random


def poll_status(url: str, timeout: float = 5.0) -> dict:
    """Mock a polling endpoint that eventually returns a completed status."""
    start = time.time()
    while time.time() - start < timeout:
        # Simulate delayed response
        time.sleep(0.2)
        # 80% chance to report …
13 0 Open
Streaming & messaging medium

How to Implement an Outbox Table Poll Publisher in Python

This code simulates an outbox pattern with a class that polls for pending records and publishes them as JSON messages, removing only those that are due.

outbox polling messaging
Python
import time
import json
from dataclasses import dataclass, asdict
from datetime import datetime, timedelta

@dataclass
class OutboxRecord:
    id: int
    topic: str
    payload: dict
    created_at: datetime

class OutboxPollPublisher:
    def __init__(self, poll_interval_seconds=1):
        self.poll_interval = poll…
11 0 Open
Big data & Spark easy

How to Mock a File Source Watch Directory in Python

Poll a directory for new files and log changes, simulating a watch directory for data ingestion patterns.

file-watching polling etl
Python
import os
import time
from pathlib import Path


def watch_directory(dir_path: str, poll_interval: float = 1.0, max_iterations: int = 5):
    """
    Mock a file-source watch directory by polling for changes.
    Returns new files detected during each poll cycle.
    """
    directory = Path(dir_path)
    directory.mk…
15 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.