Reference library

Python Code Samples

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

32 matches
Files & data easy

Audit File Permissions Across a Project in Python

Walks through every file and directory in a project tree and prints POSIX permissions plus owner UID.

file permissions os.walk audit
Python
import os
import stat
from pathlib import Path

def audit_file_permissions(project_root):
    """Walk through project_root and print path, owner, and permissions for every file."""
    results = []
    for root, dirs, files in os.walk(project_root):
        for name in files + dirs:
            full_path = os.path.joi…
56 0 Open
Files & data easy

Build a File Index by Relative Path Hash Map in Python

Recursively walk a directory and map normalized relative paths to absolute file paths using a defaultdict hash map.

os.walk file-index defaultdict
Python
import os
from collections import defaultdict


def build_file_index(root_dir):
    index = defaultdict(list)

    for dirpath, dirnames, filenames in os.walk(root_dir):
        for filename in filenames:
            full_path = os.path.join(dirpath, filename)
            relative_path = os.path.relpath(full_path, roo…
18 0 Open
Files & data easy

Build a Python Script That Detects and Deletes Empty Files Across Folders

A Python script that recursively finds and removes all zero-byte files across nested directories, returning a list of deleted paths.

filesystem cleanup pathlib
Python
import os
from pathlib import Path

def find_and_delete_empty_files(root_dir: str) -> list:
    """Find and delete all empty files under root_dir. Returns list of deleted paths."""
    deleted = []
    for file_path in Path(root_dir).rglob('*'):
        if file_path.is_file() and file_path.stat().st_size == 0:
       …
56 0 Open
Files & data easy

Compare Two Folder Structures and Find Differences in Python

Walks two directories using os.walk, builds sets of relative paths, and prints items that exist in only one folder.

filesystem os.walk comparison
Python
import os

def compare_folders(path1, path2):
    """
    Compare the file/folder structure of two directories and print differences.
    """
    def get_structure(root):
        structure = set()
        for dirpath, dirnames, filenames in os.walk(root):
            rel_path = os.path.relpath(dirpath, root)
         …
61 0 Open
Files & data easy

How to Check Disk Free Space in Python with shutil.disk_usage

This Python script uses the standard library shutil.disk_usage to report total, used, and free disk space in bytes, plus a percentage usage figure.

shutil disk usage disk space
Python
import shutil


def check_disk_free_space(path="/"):
    """Return a tuple of total, used, and free disk space in bytes."""
    usage = shutil.disk_usage(path)
    return usage.total, usage.used, usage.free


if __name__ == "__main__":
    total, used, free = check_disk_free_space()
    print(f"Total: {total:,} bytes"…
12 0 Open
Files & data easy

How to Compare Directory Trees in Python

This code recursively scans two directory trees and reports files that exist in only one directory, as well as files present in both but with different content.

filesystem comparison pathlib
Python
from pathlib import Path

def compare_directories(path1, path2):
    dir1 = Path(path1)
    dir2 = Path(path2)

    if not dir1.is_dir() or not dir2.is_dir():
        raise ValueError("Both paths must be directories.")

    files1 = {p.relative_to(dir1) for p in dir1.rglob("*") if p.is_file()}
    files2 = {p.relative…
11 0 Open
Files & data easy

How to Copy a File with shutil.copy2 in Python

Copy a file while preserving metadata like timestamps and permissions using Python's shutil.copy2 and pathlib.

shutil file-copy pathlib
Python
import shutil
from pathlib import Path

source = Path("sample.txt")
destination = Path("sample_copy.txt")

source.write_text("Hello, PythonSkillset!")

if __name__ == "__main__":
    shutil.copy2(source, destination)
    copied = destination.read_text()
    print(f"Copied content: {copied}")
    print(f"Source exists:…
11 0 Open
Files & data easy

How to Create Nested Directories with pathlib mkdir parents in Python

Create nested directories with pathlib's Path.mkdir using parents=True and exist_ok=True to avoid errors when paths already exist.

pathlib mkdir directories
Python
from pathlib import Path

def create_nested_directories(base_path: str, dirs: list[str]) -> None:
    for directory in dirs:
        path = Path(base_path) / directory
        path.mkdir(parents=True, exist_ok=True)
        print(f"Created: {path}")

if __name__ == "__main__":
    root = "output"
    nested_dirs = ["2…
13 0 Open
Files & data easy

How to Filter Files by Extension and Size in Python

Use pathlib to list files in a directory, filter by extension or minimum size, and return matching names or (name, size) pairs.

pathlib filesystem filtering
Python
from pathlib import Path

def filter_files_by_extension(directory: str, extension: str) -> list:
    """Return a list of file names in directory with the given extension."""
    path = Path(directory)
    return [f.name for f in path.iterdir() if f.is_file() and f.suffix == extension]

def filter_files_by_size(directo…
13 0 Open
Files & data medium

How to Find Duplicate Files by Size and Hash in Python

Recursively scan a directory, group files by size, then hash candidates to identify exact duplicate files.

deduplication filesystem hashlib
Python
import hashlib
from pathlib import Path

def hash_file(path, chunk_size=8192):
    hasher = hashlib.md5()
    with open(path, 'rb') as f:
        while chunk := f.read(chunk_size):
            hasher.update(chunk)
    return hasher.hexdigest()

def find_duplicates(directory):
    size_map = {}
    for path in Path(dir…
16 0 Open
Files & data easy

How to Group Files by Extension in Python

Group file names by their file extension using a dictionary and pathlib, producing a simple clear mapping for beginners.

pathlib grouping filesystem
Python
from pathlib import Path


def group_data_by_extension(files: list[Path]) -> dict[str, list[str]]:
    """Group file names by their extension."""
    grouped: dict[str, list[str]] = {}
    for file in files:
        ext = file.suffix.lower()
        grouped.setdefault(ext, []).append(file.name)
    return grouped


if…
14 0 Open
Files & data easy

How to List File Information in a Directory with Python

A helper that walks a directory and returns each file's name, size, and extension as a list of dictionaries.

pathlib filesystem file-metadata
Python
from pathlib import Path


def get_files_data(directory: str) -> list[dict]:
    """Return basic info about all files in a directory."""
    files = []
    for path in Path(directory).iterdir():
        if path.is_file():
            files.append({
                "name": path.name,
                "size": path.stat()…
12 0 Open
Files & data easy

How to List File Metadata in Python

This code walks a directory and returns a list of JSON-ready dicts with each file's name, size, and modification time.

pathlib file-metadata filesystem
Python
from pathlib import Path
import json

def format_files_data(directory_path):
    """Return a list of JSON-serializable dicts with file metadata."""
    base = Path(directory_path)
    if not base.is_dir():
        raise ValueError(f"Not a directory: {directory_path}")

    files_data = []
    for file_path in base.ite…
12 0 Open
Files & data easy

How to List Files Matching a Glob Pattern in Python

Uses pathlib.Path.glob to find and sort all files matching a glob pattern like *.py in a directory.

glob pathlib filesystem
Python
from pathlib import Path

def list_files_matching(pattern: str, directory: str = ".") -> list[str]:
    """Return sorted list of file paths matching the glob pattern in a directory."""
    return sorted(Path(directory).glob(pattern))

if __name__ == "__main__":
    # Example: list all .py files in current directory
  …
12 0 Open
Files & data easy

How to List Tar Archive Contents in Python

Open a tar archive with the stdlib tarfile module and print each entry's type, size, and name.

tarfile archive filesystem
Python
import tarfile
from pathlib import Path

def list_tar_contents(archive_path):
    """List all entries in a tar archive."""
    entries = []
    with tarfile.open(archive_path, "r") as tar:
        for member in tar.getmembers():
            entry_type = "dir" if member.isdir() else "file"
            entries.append(f"…
11 0 Open
Files & data easy

How to Parse Path Components with pathlib Path in Python

Parse a file path into parent directory, filename, stem, suffix, and parts using the standard library pathlib module.

pathlib filesystem file-paths
Python
from pathlib import Path

if __name__ == "__main__":
    p = Path("data/reports/2024/final.txt")
    print(f"Path: {p}")
    print(f"Parent: {p.parent}")
    print(f"Name: {p.name}")
    print(f"Stem: {p.stem}")
    print(f"Suffix: {p.suffix}")
    print(f"Parts: {p.parts}")
    print(f"Anchor: {p.anchor}")
    print(…
13 0 Open
Files & data easy

How to Prune Empty Directories in Python with os.walk

Remove all empty subdirectories bottom-up using os.walk with topdown=False and os.rmdir, safely ignoring non-empty folders.

os.walk filesystem cleanup
Python
import os

def prune_empty_dirs(root):
    """Remove all empty subdirectories under root, bottom-up."""
    for dirpath, dirnames, filenames in os.walk(root, topdown=False):
        if dirpath == root:
            continue
        try:
            os.rmdir(dirpath)
            print(f"Removed: {dirpath}")
        exce…
14 0 Open
Files & data easy

How to Sanitize Filenames in Python

Strip illegal filename characters and clean up names for safe filesystem use.

filenames sanitize re
Python
import re
from pathlib import Path

def sanitize_filename(filename: str, replacement: str = "_") -> str:
    """
    Remove illegal characters from a filename.
    
    Illegal characters: / \\ : * ? " < > |
    Also strips leading/trailing spaces and dots.
    """
    # Remove illegal characters
    sanitized = re.su…
12 0 Open
Files & data easy

How to Split Files by Extension in Python

Group files in a folder by their file extension into a dictionary using pathlib.

pathlib filesystem grouping
Python
from pathlib import Path

def split_files_by_extension(folder_path):
    folder = Path(folder_path)
    files_by_ext = {}

    for file_path in folder.iterdir():
        if file_path.is_file():
            ext = file_path.suffix.lower() or "no_extension"
            files_by_ext.setdefault(ext, []).append(file_path.na…
12 0 Open
Files & data medium

How to Sync Two Folders in Python (Lightweight Backup)

A Python script that synchronizes a source folder to a destination folder, copying new or updated files and removing files that no longer exist in the source.

sync backup filesystem
Python
import os
import shutil
import sys
from pathlib import Path

def sync_folders(src: Path, dst: Path):
    """Sync src folder to dst folder, copying missing/updated files."""
    dst.mkdir(parents=True, exist_ok=True)

    for src_path in src.rglob("*"):
        relative = src_path.relative_to(src)
        dst_path = ds…
37 0 Open
Files & data easy

How to Walk a Directory Tree with os.walk in Python

A generator function that recursively walks a directory tree and yields every file path found using the os.walk generator.

os.walk generators directory-tree
Python
import os


def walk_directory_tree(root_path: str):
    """Walk a directory tree and yield file paths using os.walk generator."""
    for dirpath, dirnames, filenames in os.walk(root_path):
        for filename in filenames:
            yield os.path.join(dirpath, filename)


if __name__ == "__main__":
    # Create a…
12 0 Open
Files & data easy

How to resolve a symlink to its real path in Python with pathlib

Use Path.resolve() to turn a symlink path into its absolute target path, handling relative symlinks and eliminating symbolic links.

pathlib symlink filesystem
Python
from pathlib import Path

def resolve_symlink(path):
    p = Path(path)
    return str(p.resolve())

if __name__ == "__main__":
    # Create a symlink to demonstrate the resolution
    target = Path("/tmp/real_target.txt")
    target.write_text("hello")
    link = Path("/tmp/my_link.txt")
    try:
        link.symlink…
14 0 Open
Automation & scripting medium

Automatically Clean Temporary Files from Applications Using Python

A Python script that safely deletes temporary files from common application temp directories across Windows, Linux, and macOS, tracking cleaned count and disk space.

temporary-files cleanup automation
Python
import os
import shutil
import tempfile
import platform

def clean_application_temp_files():
    """Delete common temporary file locations safely."""
    system = platform.system()
    temp_dirs = []

    if system == "Windows":
        temp_dirs.extend([
            os.path.join(os.getenv("LOCALAPPDATA"), "Temp"),
  …
56 0 Open
Automation & scripting medium

Build a Terminal Dashboard That Displays Real-Time System Performance in Python

A Python script that reads Linux system files to display a real-time terminal dashboard with CPU usage, memory usage, and CPU temperature.

linux system-monitoring terminal
Python
import os, time, sys
from collections import deque

def get_cpu_temp():
    try:
        with open("/sys/class/thermal/thermal_zone0/temp") as f:
            return round(int(f.read().strip()) / 1000, 1)
    except:
        return None

def get_mem_usage():
    with open("/proc/meminfo") as f:
        lines = f.readli…
40 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.