mmap exposes file content as a mutable or read-only byte sequence. The operating system loads pages on demand, which can help searching and random access in large files.
from mmap import ACCESS_READ, mmap
with open("events.log", "rb") as file:
with mmap(file.fileno(), length=0, access=ACCESS_READ) as data:
position = data.find(b"ERROR")
if position != -1:
print(data[position:position + 80])
How to use it safely
Open the file in a compatible mode and close the mapping before its descriptor. Do not assume mapping is always faster: buffered sequential reads may be simpler. Empty files, concurrent truncation, and Windows versus Unix differences require testing.
To strengthen the foundation, read Python collections guide and type hints guide.
The official Python documentation, accessed July 22, 2026, describes the API, edge cases, and version compatibility.