Reference library

Files & data

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

13 matches
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…
55 0 Open
Files & data medium

Find Duplicate Web Pages by Content Similarity in Python

Compute SHA-256 hashes of file contents to detect and report duplicate HTML pages or any files in a directory.

duplicate-detection hashing sha256
Python
import hashlib
import os
from collections import defaultdict

def get_file_hash(filepath):
    """Compute SHA-256 hash of file contents."""
    sha256 = hashlib.sha256()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b''):
            sha256.update(chunk)
    return sha256.hexdiges…
47 0 Open
Files & data medium

How to Atomically Write Files in Python with Temp File and Rename

Write a file atomically using a temporary file and os.replace so readers never see partial writes even if the process crashes mid-write.

atomic-write tempfile fsync
Python
import os
import tempfile
from pathlib import Path

def atomic_write(path: str | Path, content: str) -> None:
    """Write content to path atomically using a temp file and rename."""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)

    fd, temp_path = tempfile.mkstemp(
        dir=str(path.par…
17 0 Open
Files & data medium

How to Build a CSV Comparison Tool That Highlights Every Changed Cell in Python

Read two CSV files with DictReader, compare cell by cell, and return a list of dictionaries describing each changed cell using only the standard library.

csv comparison diff
Python
import csv
from pathlib import Path

def csv_cell_diff(file_a: str, file_b: str) -> list[dict]:
    rows_a = list(csv.DictReader(Path(file_a).open('r', newline='')))
    rows_b = list(csv.DictReader(Path(file_b).open('r', newline='')))
    if not rows_a or not rows_b:
        return []
    columns = list(rows_a[0].key…
41 0 Open
Files & data easy

How to Compute File SHA256 Hash with hashlib in Python

Compute the SHA256 hash of a file by reading it in chunks with hashlib and Path.open.

hashlib sha256 file-hash
Python
import hashlib
from pathlib import Path

def sha256_file(file_path: Path) -> str:
    sha256_hash = hashlib.sha256()
    with file_path.open("rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            sha256_hash.update(chunk)
    return sha256_hash.hexdigest()

if __name__ == "__main__":
    demo_fi…
16 0 Open
Files & data easy

How to Filter CSV Rows by Column Value in Python

Filter CSV rows based on a column value condition using the standard csv module and a lambda function.

csv filter file-io
Python
import csv

def filter_csv(input_file, output_file, column, condition):
    with open(input_file, newline='', encoding='utf-8') as infile, \
         open(output_file, 'w', newline='', encoding='utf-8') as outfile:
        reader = csv.DictReader(infile)
        fieldnames = reader.fieldnames
        writer = csv.Dict…
19 0 Open
Files & data medium

How to Generate Beautiful QR Codes with Embedded Logos in Python

Generate a high-error-correction QR code and paste a logo image in the center to create a branded, scannable QR code.

qrcode qrcode-generation pillow
Python
import qrcode
from PIL import Image

def generate_qr_with_logo(data, logo_path, output_path):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=4,
    )
    qr.add_data(data)
    qr.make(fit=True)

    qr_img = qr.make_image(fill_c…
52 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 easy

How to Parse NDJSON Lines into a List in Python

Reads a JSON-lines (NDJSON) file line by line and converts each non-empty line into a Python object, returning a list.

json ndjson file-io
Python
import json
from pathlib import Path


def parse_ndjson(file_path: str) -> list:
    data = []
    with Path(file_path).open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                data.append(json.loads(line))
    return data


if __name__ == "__main__"…
12 0 Open
Files & data medium

How to Stream Large CSV Files in Python

Process a large CSV file in memory-efficient chunks using Python's csv module, yielding batches of rows instead of loading everything at once.

csv streaming memory-efficient
Python
import csv
from pathlib import Path

def process_csv_in_chunks(file_path, chunk_size=1000):
    """Yield rows from a large CSV file in chunks without loading all into memory."""
    with open(file_path, 'r', newline='') as f:
        reader = csv.DictReader(f)
        chunk = []
        for row in reader:
            …
12 0 Open
Files & data easy

Normalize CSV Column Names to snake_case in Python

Convert CSV header names to snake_case using a regular expression and write the updated file in place.

csv regex snake-case
Python
import csv
import re
import sys


def to_snake_case(header):
    header = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", header)
    header = re.sub(r"[^a-zA-Z0-9]+", "_", header).strip("_").lower()
    return header


def normalize_csv_headers(input_path, output_path=None):
    with open(input_path, newline="", encoding="utf…
13 0 Open
Files & data easy

Parse Fixed Width Data File by Column Slices in Python

Extract fields from fixed-width text by slicing each line at defined column offsets, with a dictionary describing the boundaries.

fixed-width string-slicing parsing
Python
from pathlib import Path


def parse_fixed_width(data: str, slices: dict[str, tuple[int, int]]) -> list[dict[str, str]]:
    lines = data.strip().splitlines()
    records = []
    for line in lines:
        record = {}
        for name, (start, end) in slices.items():
            record[name] = line[start:end].strip()…
13 0 Open
Files & data easy

Split CSV Files into Smaller Chunks in Python

Splits a large CSV file into multiple smaller chunk files, preserving the header row in each chunk.

csv file-splitting batch-processing
Python
import csv
import os

def split_csv(input_file, chunk_size=1000, output_prefix="chunk"):
    """Split a large CSV file into smaller chunks."""
    with open(input_file, 'r', newline='') as infile:
        reader = csv.reader(infile)
        header = next(reader)
        
        file_count = 1
        row_count = 0
  …
44 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.