Reference library

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

6 matches
Files & data medium

How to Automatically Merge Hundreds of Excel Files Without Losing Formatting in Python

Merge all .xlsx files in a folder into a single Excel workbook, preserving individual sheet structures with sheet name prefixes.

excel pandas merge
Python
import pandas as pd
from pathlib import Path

def merge_excel_files(folder_path: str, output_path: str) -> None:
    """
    Merge all .xlsx files in a folder into a single Excel file,
    preserving individual sheet structures.
    """
    folder = Path(folder_path)
    excel_files = list(folder.glob("*.xlsx"))
    
…
44 0 Open
Files & data easy

How to Merge Dicts from Two JSON Files Like a Pro

This helper reads two JSON files that contain dicts, merges them with the second file overriding duplicate keys, and saves the result to a new file.

json dict merge
Python
import json
from pathlib import Path


def merge_json_files(file1: str, file2: str, output: str = "merged.json") -> dict:
    """Merge two JSON files containing dicts, with file2 overriding file1."""
    data1 = json.loads(Path(file1).read_text())
    data2 = json.loads(Path(file2).read_text())

    merged = {**data1,…
13 0 Open
Files & data easy

How to Merge Environment-Specific Config JSON in Python

Loads a base JSON config and overlays environment-specific overrides, merging the two dictionaries into one final config.

json config pathlib
Python
import json
import pathlib


def load_config(base_path: pathlib.Path, env: str) -> dict:
    base_config = json.loads(base_path.read_text())
    env_path = base_path.with_name(f"config.{env}.json")
    if env_path.exists():
        env_config = json.loads(env_path.read_text())
        return {**base_config, **env_conf…
14 0 Open
Files & data medium

How to Merge Sorted Chunk Files in Python

Merge multiple sorted text files into one sorted output file using a heap for efficient k-way merging.

heapq merge-sort external-sort
Python
import heapq


def merge_sorted_chunks(chunks, output_path):
    """Merge multiple sorted iterables into single sorted output file."""
    with open(output_path, "w") as out_f:
        # Open all chunk files
        handles = [open(chunk, "r") for chunk in chunks]
        try:
            # Heap of (value, index) tupl…
14 0 Open
Files & data medium

Join two CSV files on shared key column in Python

Merge rows from two CSV files by a common key column, outputting combined records to a new file.

csv join dictreader
Python
import csv

def join_csv(file1, file2, key, output="joined.csv"):
    # Read first CSV into dict keyed by the join column
    with open(file1, newline="") as f1:
        reader1 = csv.DictReader(f1)
        data1 = {row[key]: row for row in reader1}

    # Read second CSV and merge matching rows
    with open(file2, n…
15 0 Open
Files & data easy

Merge Multiple PDF Files into One Document in Python

Combines multiple PDF files into a single PDF document using the PyPDF2 library's PdfMerger class.

pdf pypdf2 file-merging
Python
import PyPDF2

def merge_pdfs(input_paths, output_path):
    merger = PyPDF2.PdfMerger()
    for path in input_paths:
        merger.append(path)
    merger.write(output_path)
    merger.close()
    print(f"Merged {len(input_paths)} PDFs into '{output_path}'.")

if __name__ == "__main__":
    files = ["file1.pdf", "fi…
42 0 Open

Browse by section

Each section groups closely related Python snippets.

Files & data — Python code examples

What you will find here

This page collects files & data snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.