Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import mmap
- import os
- def edit_in_place(path, offset, data):
- """
- Edits a file in-place using mmap
- :param path: Path of file
- :param offset: Start offset
- :param data: Data
- """
- if isinstance(data, str):
- data = data.encode('utf-8')
- mmap_offset = mmap.ALLOCATIONGRANULARITY * (offset // mmap.ALLOCATIONGRANULARITY)
- offset = offset % mmap.ALLOCATIONGRANULARITY
- end = offset + len(data)
- with open(path, 'r+b') as f:
- mm = mmap.mmap(f.fileno(), end, offset=mmap_offset)
- mm[offset:end] = data
- mm.flush()
- mm.close()
- # update modified time of file
- os.utime(f.fileno() if os.utime in os.supports_fd else path)
Add Comment
Please, Sign In to add comment