Advertisement
rfmonk

mmap_write_copy.py

Jan 28th, 2014
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. #1/usr/bin/env python
  2.  
  3. # this is from The Python
  4. # Standard Library by example
  5. # ISBN13: 9780321767349
  6.  
  7. import mmap
  8. import shutil
  9. import contextlib
  10.  
  11. # Copy the example file
  12. shutil.copyfile('lorem.txt', 'lorem_copy.txt')
  13.  
  14. word = 'consectetuer'
  15. reversed = word[::-1]
  16.  
  17. with open('lorem_copy.text', 'r+') as f:
  18.     with contextlib.closing(mmap.mmap(f.fileno(), 0,
  19.                                       access=mmap.ACCESS_COPY)) as m:
  20.  
  21.         print 'Memory Before:'
  22.         print m.readline().rstrip()
  23.         print 'File Before  :'
  24.         print f.readline().rstrip()
  25.         print
  26.  
  27.         m.seek(0)  # rewind
  28.         loc = m.find(word)
  29.         m[loc:loc + len(word)] = reversed
  30.  
  31.         m.seek(0)  # rewind
  32.         print 'Memory After :'
  33.         print m.readline().rstrip()
  34.  
  35.         f.seek(0)
  36.         print 'File After  :'
  37.         print f.readline().rstrip()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement