mmap Maps Files Without Full Reads
Map a file into memory with mmap, patch bytes in place, and observe read-only mappings reject writes with TypeError.
Code
import mmap
import tempfile
from pathlib import Path
def main() -> None:
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / 'journal.bin'
path.write_bytes(b'0000HEADER\nfirst record\nsecond record\n')
with path.open('r+b') as handle:
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_WRITE) as view:
print('mapped bytes:', len(view))
print('header:', view[:10].decode('ascii'))
view[4:10] = b'UPDATE'
print('patched:', view[:10].decode('ascii'))
print('second record at:', view.find(b'second'))
print('on disk:', path.read_bytes()[:10].decode('ascii'))
with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as handle:
handle.write(b'read only payload')
name = handle.name
with open(name, 'rb') as handle:
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as view:
try:
view[0] = 65
except TypeError as exc:
print('read-only write blocked:', type(exc).__name__)
Path(name).unlink()
if __name__ == '__main__':
main()Inside the snippet
mmap Maps Files Without Full Reads is built around the function main.
From mmap it pulls Path — the imports name exactly which library surface the snippet touches.
What to watch for
- Plan for an install step:
mmapis a real dependency, resolved by the package manager.
Putting it to use
Look for the mapped bytes:, header:, patched: prefixes when the file runs; they tie each line to its step.
Core lines
with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as handle:
handle.write(b'read only payload')
name = handle.name
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_WRITE) as view:
print('mapped bytes:', len(view))
print('header:', view[:10].decode('ascii'))
view[4:10] = b'UPDATE'
print('patched:', view[:10].decode('ascii'))
print('second record at:', view.find(b'second'))
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as view:
try:
view[0] = 65
except TypeError as exc:
print('read-only write blocked:', type(exc).__name__)
Interactive Tools for This Topic
Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there third-party dependencies?
- `mmap` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.