Reference library

Python Code Samples

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

3 matches
Files & data easy

Rotate Log Files in Python by Size

This code rotates a log file when its size exceeds a threshold, keeping a specified number of backups.

log-rotation files os
Python
import os
import glob
from pathlib import Path

def rotate_log(log_path, max_size_bytes=1024, max_backups=3):
    log_file = Path(log_path)
    if log_file.stat().st_size <= max_size_bytes:
        print(f"Log size {log_file.stat().st_size} bytes <= threshold, no rotation")
        return

    for i in range(max_backu…
13 0 Open
Automation & scripting medium

Python: Archive Old Logs by Compressing Gzip by Age

A Python script that finds .log files older than a specified age and compresses them into .gz archives while removing the originals.

gzip log-rotation automation
Python
import gzip
import os
import shutil
from pathlib import Path


def archive_logs(log_dir: str, max_age_days: int) -> list[str]:
    """Compress log files older than max_age_days into .gz archives.
    
    Returns a list of compressed file paths.
    """
    cutoff = time.time() - max_age_days * 86400
    compressed = …
14 0 Open
Observability & SRE easy

Rotate Log Files by Size in Python

A mock log rotation script that renames log files exceeding a size threshold, appending numbered backups.

log-rotation pathlib file-management
Python
import os
from pathlib import Path

def rotate_logs(directory: str, max_size: int = 100) -> None:
    """Rotate log files that exceed max_size bytes."""
    log_dir = Path(directory)
    for log_file in sorted(log_dir.glob("*.log"), key=lambda p: str(p)):
        if log_file.stat().st_size > max_size:
            for …
13 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.