Reading Huge Files Without Loading Them: Python's mmap Module
This article explains how Python's mmap module maps a file into memory so that it can be searched, sliced and modified without reading it whole, measures the gain in random access, and describes the pitfalls of memory-mapped files.
The present article addresses memory-mapped files through the module mmap, which serves the common need to search or read parts of a file too large to be loaded comfortably with open().read(). Large open-world games face the same problem with their terrain: instead of loading the whole world when play begins, they stream from disk only the region around the player and discard what is left behind. This means that a memory map makes the whole file addressable as a sequence of bytes, while the operating system loads into memory only the pages, blocks of a few kilobytes, that the program actually touches. The analogy, however, stops at this point, because a game predicts where the player will go and loads ahead, whereas a map loads a page only when it is accessed, so a search that touches every byte still reads the entire file from disk. Reading and modifying a large file through slices, without copying it into the memory of the process, is the secret weapon of the module mmap.
Mapping a File for Reading
A map is created from the descriptor of an open file, and the argument length=0 maps the file in full. The resulting object supports indexing, slicing, find and the regular expressions of the module re, as if it were a bytes object, and it also offers the file methods seek and read. The following example writes a file of 5 megabytes into a temporary directory, searches it through a map, and compares the memory that Python allocates with the memory required by reading the whole file.
import mmap
import os
import re
import tempfile
import tracemalloc
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "data.bin")
with open(path, "wb") as f:
f.write(b"x" * 5_000_000 + b"SECRET_CODE=4242\n")
tracemalloc.start()
with open(path, "rb") as f:
position = f.read().find(b"SECRET")
read_peak = tracemalloc.get_traced_memory()[1]
tracemalloc.reset_peak()
with open(path, "rb") as f:
with mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_READ) as mm:
print(mm.find(b"SECRET") == position) # Output: True
print(re.search(rb"SECRET_CODE=(\d+)", mm).group(1)) # Output: b'4242'
print(mm[position:position + 6]) # Output: b'SECRET'
map_peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
print(read_peak > 4_000_000, map_peak < 100_000) # Output: True True
Reading the file allocated a bytes object as large as the file itself, whereas searching the map allocated almost nothing inside Python, because the bytes remain in pages managed by the operating system. These pages are not free: they occupy the system's page cache while they are in use, although the system can discard them under pressure and read them again later, which is what allows a 64-bit process to map files larger than its physical memory. A map also exposes the buffer protocol, so memoryview and struct.unpack_from can read records from it without copying, as described in the article devoted to memoryview and in the article devoted to the module struct.
Writing Through a Map
The access mode decides what an assignment does. ACCESS_READ forbids it, ACCESS_WRITE writes the change through to the file, and ACCESS_COPY keeps the change in a private copy of the pages and leaves the file intact. A writable map requires a file opened for update, in mode r+b, and the documentation states that, without a call to flush, there is no guarantee that the changes reach the file before the map is destroyed. The following example applies the same assignment in both writable modes and attempts to change the length of a slice.
import mmap
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "small.txt")
with open(path, "wb") as f:
f.write(b"hello world")
with open(path, "r+b") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_COPY) as mm:
mm[0:5] = b"HELLO"
print(mm[:]) # Output: b'HELLO world'
with open(path, "rb") as f:
print(f.read()) # Output: b'hello world'
with open(path, "r+b") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_WRITE) as mm:
mm[0:5] = b"HELLO"
mm.flush()
try:
mm[0:5] = b"HI"
except IndexError as error:
print(error) # Output: mmap slice assignment is wrong size
with open(path, "rb") as f:
print(f.read()) # Output: b'HELLO world'
A slice assignment must preserve the length of the slice, because the map has a fixed size; growing the file requires resize, which is not available for read-only or copy-on-write maps and may fail on Windows while other maps of the same file exist. Several processes can map the same file with ACCESS_WRITE and observe each other's changes, but the module provides no locking, so concurrent writers must coordinate through other means.
Pitfalls of Memory-Mapped Files
A map behaves like a sequence of bytes, but it remains a resource of the operating system with its own rules, which produces the following six pitfalls:
- Empty files. Mapping a file of length zero with
length=0raisesValueError, so empty inputs must be handled before mapping. - Exported buffers. A
memoryviewof the map preventsclose()withBufferErroruntil the view is released. - Aligned offsets. The
offsetargument must be a multiple ofmmap.ALLOCATIONGRANULARITY, which equals the page size on Unix, usually 4,096 bytes, and is 65,536 bytes on Windows. - Files locked by the map. On Windows, a mapped file cannot be deleted or truncated while the map is open, even after the file object has been closed.
- Bytes, not text. A map holds bytes, so search terms must be encoded and decoding a slice is the program's responsibility, including multibyte characters cut at a boundary.
- Sequential reads. For a single pass over a file, reading in chunks with
readis as effective as a map; the advantage of a map lies in random access and in searches without a copy.
The first three pitfalls, together with a measurement of random access, are reproduced in the following example, which takes a few seconds because it reads 10,000 positions twice.
import mmap
import os
import random
import tempfile
import timeit
with tempfile.TemporaryDirectory() as folder:
empty = os.path.join(folder, "empty.bin")
open(empty, "wb").close()
with open(empty, "rb") as f:
try:
mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
except ValueError as error:
print(error) # Output: cannot mmap an empty file
path = os.path.join(folder, "data.bin")
with open(path, "wb") as f:
f.write(os.urandom(5_000_000))
positions = [random.randrange(4_999_000) for _ in range(10_000)]
with open(path, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
view = memoryview(mm)
try:
mm.close()
except BufferError as error:
print(error) # Output: cannot close exported pointers exist
view.release()
try:
mmap.mmap(f.fileno(), 100, access=mmap.ACCESS_READ, offset=100)
except OSError as error:
print(type(error).__name__) # Output: OSError
def with_seek():
for p in positions:
f.seek(p)
f.read(16)
def with_slice():
for p in positions:
mm[p:p + 16]
t_seek = min(timeit.repeat(with_seek, number=3, repeat=3))
t_slice = min(timeit.repeat(with_slice, number=3, repeat=3))
print(t_seek > 5 * t_slice) # Output: True
On CPython 3.12 under Windows, with a file of 50 megabytes already in the page cache, 10,000 reads of 16 bytes took about 54 milliseconds with seek and read on a buffered file, 36 on an unbuffered one, and 0.5 through slices of the map, because each read call crosses into the operating system while a slice only copies bytes that are already mapped. Searching the whole file with find took about 26 milliseconds on the map against 46 for reading it and then searching the copy. With a cold cache, the disk dominates both measurements, so these figures describe the cost of the calls rather than the cost of the storage.
Choosing How to Read a Large File
Consequently, a map suits random access and in-place searches over large files, while sequential processing keeps the ordinary file methods, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Small files read in full | open().read() |
| Line-by-line or sequential processing | Iteration over the file or read in chunks |
| Searches over a large file | mmap with find or re |
| Random access to records at known offsets | mmap with slices or struct.unpack_from |
| Modifying bytes in place without changing the size | mmap with ACCESS_WRITE and flush |
| Experimental changes that must not touch the file | mmap with ACCESS_COPY |
| Data shared between processes without a file | multiprocessing.shared_memory |
Conclusion
It is concluded that the module mmap makes a file addressable as a sequence of bytes, that the operating system loads only the pages that are accessed, and that the access mode decides whether an assignment is forbidden, written through or kept private. This magic has limits: empty files cannot be mapped, slices cannot change the size, offsets must be aligned, and a full scan still reads the whole file. Counting occurrences of hashable values with collections.Counter, including its arithmetic between counters and its most common elements, is the subject of a future article of this series.