Guest User

Untitled

a guest
Jan 4th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. import mmap
  2. import os
  3.  
  4.  
  5. def edit_in_place(path, offset, data):
  6. """
  7. Edits a file in-place using mmap
  8. :param path: Path of file
  9. :param offset: Start offset
  10. :param data: Data
  11. """
  12. if isinstance(data, str):
  13. data = data.encode('utf-8')
  14. mmap_offset = mmap.ALLOCATIONGRANULARITY * (offset // mmap.ALLOCATIONGRANULARITY)
  15. offset = offset % mmap.ALLOCATIONGRANULARITY
  16. end = offset + len(data)
  17. with open(path, 'r+b') as f:
  18. mm = mmap.mmap(f.fileno(), end, offset=mmap_offset)
  19. mm[offset:end] = data
  20. mm.flush()
  21. mm.close()
  22. # update modified time of file
  23. os.utime(f.fileno() if os.utime in os.supports_fd else path)
Add Comment
Please, Sign In to add comment