二进制文件内存映射

点击查看代码
# 对二进制文件做内存映射
# 使用 mmap 模块对文件进行内存有映射操作
import mmap
import os.path


def memory_map(filename, access=mmap.ACCESS_WRITE):
    """

    :param filename:
    :param access: mmap.ACCESS_WRITE: 读写
                   mmap.ACCESS_READ:  只读
                   mmap.ACCESS_COPY: 更改不会保存到原文件
    :return:
    """
    size = os.path.getsize(filename)
    fd = os.open(filename, os.O_RDWR)
    return mmap.mmap(fd, size, access=access)


# make test data
size = 100000
with open("data", "wb") as f:
    f.seek(size - 1)
    f.write(b"\x00")

# test
with memory_map("data") as m:
    print(len(m))  # 100000
    print(m[:10])  # b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    print(m[0])  # 0
    m[0:11] = b"Hello World"

# verify
with open("data", "rb") as f:
    print(f.read(11))  # b'Hello World'

posted @ 2024-04-27 14:24  一枚码农  阅读(5)  评论(0编辑  收藏  举报