Complete the code to create a memory-mapped file in Python.
import mmap with open('example.txt', 'r+b') as f: mm = mmap.mmap(f.fileno(), [1]) print(mm.readline())
The size parameter in mmap.mmap specifies the number of bytes to map. Using 1024 maps 1 KB of the file.
Complete the code to open a memory-mapped file with read-only access.
import mmap with open('data.bin', 'rb') as f: mm = mmap.mmap(f.fileno(), 0, access=[1]) print(mm.read(10))
Using mmap.ACCESS_READ opens the memory map with read-only access, preventing modifications.
Fix the error in the code to correctly map the entire file size.
import os import mmap filename = 'logfile.log' size = os.path.getsize(filename) with open(filename, 'r+b') as f: mm = mmap.mmap(f.fileno(), [1]) print(mm[:10])
The size variable holds the file size, which should be passed to mmap to map the entire file.
Fill both blanks to create a memory-mapped file and write data to it.
import mmap with open('file.dat', 'r+b') as f: mm = mmap.mmap(f.fileno(), [1], access=[2]) mm[0:5] = b'Hello' mm.flush()
Mapping 10 bytes with ACCESS_WRITE allows writing data and flushing changes to the file.
Fill all three blanks to create a memory-mapped file, read a slice, and close it properly.
import mmap with open('sample.txt', 'r+b') as f: mm = mmap.mmap(f.fileno(), [1], access=[2]) data = mm[[3]:[3]+5] print(data) mm.close()
Mapping 20 bytes with read access and reading from offset 0 to 5 bytes correctly reads data from the file.