How to Use mmap for Fast File I/O Operations in Python

1. Memory-Mapping a File for Reading

import mmap

# Open file in read mode
with open(“large_file.txt”, “r”) as f:
# Memory-map the file (read-only mode)
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
# Read contents as bytes
print(mm[:100]) # Read first 100 bytes
print(mm.find(b”search_term”)) # Find a term

2.Memory-Mapping a File for Writing

import mmap

# Open file in read/write mode
with open(“data.txt”, “r+b”) as f:
with mmap.mmap(f.fileno(), 0) as mm:
# Modify the file in place
mm[0:5] = b”Hello” # Replace first 5 bytes
mm.flush() # Ensure changes are written to disk

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top