Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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.
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…
How to Monitor Process RSS Memory in Python
Poll the VmRSS field from /proc/PID/status to watch a process's resident memory and alert on growth.
import os
import time
import subprocess
import sys
def get_rss_mb(pid):
"""Return RSS memory in MB for a given process ID."""
try:
with open(f"/proc/{pid}/status", "r") as f:
for line in f:
if line.startswith("VmRSS:"):
return int(line.split()[1]) / 1024…
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.
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(…
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 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.
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 …
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.
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…
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.