On this page
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
- Mapping an empty (0-byte) file raises
ValueError: cannot mmap an empty file: Always checkpath.stat().st_size > 0first. - Always use
with mmap.mmap(...) as mm:: Unclosed mappings hold OS virtual memory and prevent file deletion on Windows. - Use
access=mmap.ACCESS_READfor read-only scans (orACCESS_COPYfor copy-on-write edits that don't modify disk). - Bytes only:
mmapoperates on rawbytes, not decodedstr.
Classes & Objects
- mmap.error โ Base class for I/O related errors. (Methods:
.add_note(),.with_traceback()) - mmap.mmap โ Windows: mmap(fileno, length[, tagname[, access[, offset]]]) Maps length bytes from the file specified by the file handle fileno, and returns a mmap object. If length is larger than the current size (Methods:
.close(),.find(),.flush(),.madvise(),.move(),.read())
Constants & Attributes
mmap.ACCESS_COPY(int) =3mmap.ACCESS_DEFAULT(int) =0mmap.ACCESS_READ(int) =1mmap.ACCESS_WRITE(int) =2mmap.ALLOCATIONGRANULARITY(int) =16384mmap.MADV_DONTNEED(int) =4mmap.MADV_FREE(int) =5mmap.MADV_FREE_REUSABLE(int) =7mmap.MADV_FREE_REUSE(int) =8mmap.MADV_NORMAL(int) =0mmap.MADV_RANDOM(int) =1mmap.MADV_SEQUENTIAL(int) =2mmap.MADV_WILLNEED(int) =3mmap.MAP_32BIT(int) =32768mmap.MAP_ANON(int) =4096
Linked from
Related notes
- tuts/python3/stdlib_module/mimetypes Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/modulefinder Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/getopt Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/io Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/mmap/error Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/mmap/mmap Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/os Linked here; shared tags: #stdlib