RUNTIME VALUE CONVERSIONS

Memory-mapped files

Use *import mmap to search a binary file, edit a fixed-size field in place or work with anonymous memory. The generated program opens the mapping when it runs.

Edit a file and check the bytes

Select Transpile → Runtime in the workspace. The example creates or replaces header.bin in the program’s working directory. Run it in an empty directory. Flush the buffered file before mapping the bytes just written.

*import mmap as mm
def main():
    with open("header.bin", "w+b") as f:
        f.write(b"HEADdata")
        f.flush()
        with mm.mmap(f.fileno(), 0, access=mm.ACCESS_WRITE) as view:
            view[:4] = b"INFO"
            print(view.find(b"data"), view[:4])
            while chunk := view.read(4):
                print(chunk)
            view.flush()
    return 0

The search finds data at byte offset 4. The first slice changes the header without moving the cursor, so the loop starts at byte zero. Output is:

4 b'INFO'
b'INFO'
b'data'

After both contexts close, header.bin contains exactly INFOdata. For an existing nonempty file, open it in r+b and omit the seed write. See the Python API or build a standalone program for other ways to run this example.

Choose the access mode

TaskOpen and mapEffect
Inspect an existing filerb and mm.ACCESS_READRead or search its bytes. A write raises TypeError.
Update a file in placer+b and mm.ACCESS_WRITEShared views can see changes. Use flush() to request writeback.
Try a private editrb and mm.ACCESS_COPYChanges stay in this view. Flushing a private view preserves the original file.
Use scratch memorymm.mmap(-1, 4096)Creates an anonymous 4 KiB mapping. Use len(view) to get its length.

Use f.fileno() on a live Runtime file. Length 0 maps a nonempty file from the chosen offset to its end. For a window into a larger file, pass its byte length and an offset= aligned to mm.ALLOCATIONGRANULARITY. Use len(view) for the window length and view.size() for the backing file length. The file and map have independent cursors and lifetimes.

Read, write or search from a known position

OperationResultCursor
read(n), readline()Independent bytes, or b"" at EOF. read_byte() returns an integer and raises ValueError at EOF.Advances by the number of bytes read.
write(data), write_byte(n)Overwrite within a writable view. write returns the byte count. write_byte accepts 0–255 and returns None.Advances past the write.
seek(offset, whence), tell()Use 0 for start, 1 for current, 2 for end. The supported Python 3.12 interface returns None from seek and an integer from tell.Only seek moves it.
find(needle, start, end), rfind(...)Return a byte offset or -1. An omitted start uses the current position. Pass 0 to search the whole view.Preserved.
view[i], view[a:b], move(dest, src, count)An index returns an integer. A slice returns independent bytes. Slice writes require equal lengths. move handles overlapping regions.Preserved.

Read a record and try a private edit

*import mmap as mm
*import struct as wire

def main():
    with open("counter.bin", "wb") as output:
        output.write(wire.pack(">I", 42))
    with open("counter.bin", "rb") as source:
        with mm.mmap(source.fileno(), 0, access=mm.ACCESS_COPY) as view:
            print(wire.unpack(">I", view[:4])[0])
            view[:4] = wire.pack(">I", 7)
            print(wire.unpack(">I", view[:4])[0])
        print(wire.unpack(">I", source.read(4))[0])
    return 0

This example creates or replaces counter.bin. It prints 42, 7, then 42, each on its own line. The four bytes on disk remain 00 00 00 2a. See record formats and byte order.

Troubleshoot a mapping