隨機檔案訪問使用 mmap

使用 mmap 模組允許使用者通過將檔案對映到記憶體中來隨機訪問檔案中的位置。這是使用普通檔案操作的替代方法。

import mmap

with open('filename.ext', 'r') as fd:
    # 0: map the whole file
    mm = mmap.mmap(fd.fileno(), 0)

    # print characters at indices 5 through 10
    print mm[5:10]

    # print the line starting from mm's current position
    print mm.readline()

    # write a character to the 5th index
    mm[5] = 'a'

    # return mm's position to the beginning of the file
    mm.seek(0)

    # close the mmap object
    mm.close()