Files
Python_CookBook_repo/5.文件与IO/10.对二进制文件做内存映射.py
2025-09-10 16:12:45 +08:00

45 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import mmap
if __name__ == '__main__':
def memory_map(file_path, access=mmap.ACCESS_WRITE):
size = os.path.getsize(file_path)
fild_data = os.open(file_path, os.O_RDWR)
return mmap.mmap(fild_data, size, access=access)
SIZE = 1000000
# with open(r'5.文件与IO/10.data', 'wb') as f:
# f.seek(SIZE - 1)
# f.write(b'\x00')
m = memory_map('5.文件与IO/10.data')
print(len(m))
m[0:11] = b'Hello World'
m.close()
with open(r'5.文件与IO/10.data', 'rb') as f:
print(f.read(11))
# 当然这个函数得益于他的open内嵌也能在with的上下文中打开并自动关闭
with memory_map('5.文件与IO/10.data') as m:
print(len(m))
print(m.closed)
# 当然如果你想只读可以在access里设置成mmp.ACCESS_READ,
# 如果只想把文件拷贝到内存而不是直接在文件里修改mmp.ACCESS_COPY非常有用
# mmap和memoryview又有所不同
m = memory_map('5.文件与IO/10.data')
v = memoryview(m).cast('I')
v[0] = 7
m[0:4] = b'\x07\x01\x00\x00'
print(m[0:4])
print(v[0])
# 可以看出来memoryview在做转换的时候用的是小端存储
print(int.from_bytes(m[0:4], byteorder='little'))
print(int.from_bytes(m[0:4], byteorder='big'))
v.release()
m.close()