Reference library

Python Code Samples

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

8 matches
Strings & text easy

How to Check if a String Ends with a File Extension in Python

This code checks whether a filename ends with any of a list of file extensions, handling case insensitivity.

file-extension string-methods endswith
Python
def ends_with_extension(filename, extensions):
    """Check if a filename ends with any of the given extensions."""
    lower_name = filename.lower()
    return any(lower_name.endswith(ext.lower()) for ext in extensions)

if __name__ == "__main__":
    # Test cases
    test_files = ["report.pdf", "image.PNG", "script.…
17 0 Open
Files & data easy

Convert All Markdown Files in a Folder to HTML in Python

Batch convert every .md file in a folder to .html using the `markdown` library with the 'extra' extensions.

markdown html batch-conversion
Python
import os
import markdown
from pathlib import Path

def convert_md_folder_to_html(input_folder="markdown_files", output_folder="html_pages"):
    input_path = Path(input_folder)
    output_path = Path(output_folder)
    output_path.mkdir(exist_ok=True)
    
    for md_file in input_path.glob("*.md"):
        with open…
54 0 Open
Files & data easy

Count Files by Extension in Python

Count files in a directory grouped by file extension using Python's standard library.

files pathlib directory
Python
from pathlib import Path

def count_files_by_extension(directory: str) -> dict[str, int]:
    """Count files in a directory grouped by file extension."""
    data = {}
    for path in Path(directory).iterdir():
        if path.is_file():
            ext = path.suffix.lower() or "(no extension)"
            data[ext] =…
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
Automation & scripting easy

How to Quarantine Suspicious Files in Python

Move files with suspicious extensions to a quarantine folder using pathlib and shutil for safe isolation.

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

def quarantine_files(source_dir, quarantine_dir, suspicious_extensions):
    """
    Move files with suspicious extensions to a quarantine folder.
    Returns list of moved files.
    """
    source_path = Path(source_dir)
    quarantine_path = Path(quarantine_dir)
   …
11 0 Open
Automation & scripting easy

How to automatically organize your Downloads folder by file type in Python

This script scans the Downloads folder and moves files into sub-folders based on their extensions (e.g., Images, Documents, Videos).

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

def organize_downloads_folder(downloads_path=None):
    if downloads_path is None:
        downloads_path = str(Path.home() / "Downloads")
    
    if not os.path.exists(downloads_path):
        print(f"Path {downloads_path} does not exist.")
        return
    
    fi…
39 0 Open
Git + Python easy

How to Generate Git LFS Extension Patterns in Python

This script builds mock Git LFS file patterns for common geospatial extensions and filters them based on compression suffixes.

git lfs geospatial
Python
import itertools
import re

LFS_EXTENSIONS = {".csv", ".geojson", ".tif", ".shp", ".gpkg"}

def build_mock_lfs_pattern(base_name="data_usgs_lidar"):
    patterns = []
    for ext in sorted(LFS_EXTENSIONS):
        for variant in (("", ".lz4"), (".compressed",), (".b", ".a"), ("_v1", ".zip")):
            full_pattern …
11 0 Open
Modern tooling easy

How to Generate a Mock devcontainer.json Config in Python

Build a reproducible devcontainer.json file with Python, composing name, image, extensions, forwarded ports, and a post-create command as a dict.

devcontainer json config
Python
import json
from pathlib import Path


def create_devcontainer_config(
    image: str = "mcr.microsoft.com/devcontainers/python:3.11",
    name: str = "python-dev-container",
    ports: list[int] | None = None,
    post_create: str | None = None,
) -> dict:
    config = {
        "name": name,
        "image": image,
…
14 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.