objectif
Accéder à des segments de fichier sans tout charger en mémoire.
code minimal
import mmap, tempfile, os
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(b"0123456789"*100)
path = f.name
with open(path, "r+b") as f:
with mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_READ) as mm:
chunk = mm[10:20]
print(chunk == b"0123456789") # attendu: True
os.remove(path)
utilisation
import mmap
print(hasattr(mmap, "mmap"))
variante(s) utile(s)
import mmap, tempfile, os
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(b"abc")
path = f.name
with open(path, "r+b") as f:
with mmap.mmap(f.fileno(), 0) as mm:
mm[0] = ord("A")
print(True)
os.remove(path)
notes
- length=0 mappe tout le fichier; privilégiez un offset/longueur pour très gros.
- Sur Windows, ouvrez en “r+b” pour autoriser le mapping.