Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2007 Doug Hellmann.
  4. #
  5. """Writing to a memory mapped file using a slice assignment.
  6.  
  7. """
  8.  
  9. __version__ = "$Id$"
  10. #end_pymotw_header
  11.  
  12. import mmap
  13. import shutil
  14. import contextlib
  15.  
  16. # Copy the example file
  17. shutil.copyfile('lorem.txt', 'lorem_copy.txt')
  18.  
  19. word = 'consectetuer'
  20. reversed = word[::-1]
  21. print 'Looking for :', word
  22. print 'Replacing with :', reversed
  23.  
  24. with open('lorem_copy.txt', 'r+') as f:
  25. with contextlib.closing(mmap.mmap(f.fileno(), 0)) as m:
  26. print 'Before:'
  27. print m.readline().rstrip()
  28. m.seek(0) # rewind
  29.  
  30. loc = m.find(word)
  31. m[loc:loc+len(word)] = reversed
  32. m.flush()
  33.  
  34. m.seek(0) # rewind
  35. print 'After :'
  36. print m.readline().rstrip()
  37.  
  38. f.seek(0) # rewind
  39. print 'File :'
  40. print f.readline().rstrip()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement