On this page
  1. mmap
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Regex Searching a Large File Without Loading It into RAM
  7. Gotchas & Boundaries
  8. Classes & Objects
  9. Constants & Attributes

mmap

Prev: mimetypes | Up: stdlib_module | Next: modulefinder
Rel: os, io, time, argparse, getopt
Ref: docs.python.org โ€” mmap
Tags: #public #python3 #stdlib


Import

import mmap

Overview

Memory-maps a file directly into the process's virtual address space (mmap.mmap), letting you slice, search (find, re.search), or edit multi-gigabyte binary files with zero full-file reads into Python heap memory.

Quick Start

import mmap
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    p = Path(tmp) / "sample.bin"
    p.write_bytes(b"HEADER:hello world:END")
    with p.open("rb") as fh:
        with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as mm:
            idx = mm.find(b"hello")
            assert idx == 7 and mm[idx:idx + 11] == b"hello world"

Implementation Walkthrough

1. Regex Searching a Large File Without Loading It into RAM

mmap objects implement the buffer protocol, so re binary patterns (rb"...") run directly over the mapped file:

import mmap
import re
from pathlib import Path

def count_pattern_in_file(path: Path, pattern: bytes) -> int:
    if path.stat().st_size == 0:
        return 0
    rx = re.compile(pattern)
    with path.open("rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as mm:
        return sum(1 for _ in rx.finditer(mm))

Gotchas & Boundaries

Classes & Objects

Constants & Attributes

Linked from

Related notes