點選檢視程式碼
# 對二進位制檔案做記憶體對映
# 使用 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'