Reference library

Python Code Samples

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

5 matches
Files & data medium

How to Automatically Extract Every Archive in a Folder with Python

Walk through a folder and extract all ZIP, RAR, and 7Z archives into separate subdirectories using Python.

zipfile rarfile py7zr
Python
import zipfile
import rarfile
import py7zr
import pathlib

def extract_archives(folder: str):
    """Extract every ZIP, RAR, and 7Z archive in the given folder."""
    folder_path = pathlib.Path(folder)
    for archive_file in folder_path.iterdir():
        suffix = archive_file.suffix.lower()
        try:
           …
38 0 Open
Files & data easy

How to Delete a File if it Exists in Python

Delete a file safely in Python using pathlib's Path.unlink, checking existence first to avoid errors.

pathlib file-deletion file-management
Python
from pathlib import Path

def delete_file_if_exists(file_path: str) -> bool:
    """Delete a file if it exists. Returns True if deleted, False if not found."""
    path = Path(file_path)
    if path.exists():
        path.unlink()
        print(f"Deleted: {path}")
        return True
    else:
        print(f"File not…
14 0 Open
Automation & scripting easy

How to Auto Organize Downloads by File Extension in Python

A Python script that sorts files in a directory into subfolders based on their file extensions, creating folders automatically.

file-organization automation pathlib
Python
import os
import shutil
from pathlib import Path

def organize_downloads(download_dir="~/Downloads"):
    """Move files in a directory into subfolders based on file extension."""
    download_path = Path(download_dir).expanduser()
    
    if not download_path.exists():
        print(f"Directory not found: {download_p…
13 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
Database scaling & optimization easy

Simulate PostgreSQL Vacuum to Reclaim Space in Python

A Python class that safely rewrites a data file to remove deleted rows and reclaim physical space, mimicking PostgreSQL's VACUUM operation.

vacuum file-management database
Python
import shutil
import os

class VacuumCleaner:
    """Simulates PostgreSQL-style vacuum reclaiming dead space in a file."""
    
    def __init__(self, filepath, fill_ratio=0.7, dead_marker="[DELETED]"):
        self.filepath = filepath
        self.fill_ratio = fill_ratio
        self.dead_marker = dead_marker
    
  …
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.