Skip to content

Instantly share code, notes, and snippets.

@kshirsagarsiddharth
Created August 3, 2020 08:34
Show Gist options
  • Select an option

  • Save kshirsagarsiddharth/af5e16ca61f83ba02b76d7f7136ef3e0 to your computer and use it in GitHub Desktop.

Select an option

Save kshirsagarsiddharth/af5e16ca61f83ba02b76d7f7136ef3e0 to your computer and use it in GitHub Desktop.
mmap intro
import mmap
with open("hello.txt","wb") as f:
f.write(b"Writing")
f = open("hello.txt","r+b")
mm = mmap.mmap(f.fileno(),0)
print(mm.readline())
#Output: b'Writing'
print(mm[:5])
#Output: b'Writi'
mm[5:] = b"a7"
# we cannot exceed the allocated bytes
# so if I add some extra bytes
mm[5:] = b"writing extra bytes"
"""
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
in
3
4 # so if I add some extra bytes
----> 5 mm[5:] = b"writing extra bytes"
6 mm.close()
IndexError: mmap slice assignment is wrong size
"""
mm.close()
---------------------------------------------------------------------------------------------------------------------------
#To map anonymous memory, -1 should be passed as the fileno along with the length.
# Using with the with statement
import mmap
with mmap.mmap(-1,20) as mm:
mm.write(b"Hello Worlllld")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment