example needed using mmap function in python
I am seeking an example in python to memory map a 1gb file. Does anyone have an example I can use?
The file can be any 开发者_JAVA技巧random text. I just want to look to see what is the proper way to do this...
Here is an example that can help you understand mmap in python (3.0+)
The code below opens a file, then memory maps it. It exercises the readline() method of the mapped file, demonstrating that it works just as with a standard file. It then reads and writes slices of the mapped file (an equally valid way to access the mapped file's content, which does not alter the file pointer). Finally the file pointer is re-positioned at the start and the (updated) contents are read in. (The "14" is the return value of the write() function, which always returns the number of bytes written.)
>>> with open("myfile.txt", "wb") as f:
... f.write(b"Hello Python!\n")
>>> import mmap
>>> with open("myfile.txt", "r+b") as f:
... mapf = mmap.mmap(f.fileno(), 0)
... print(mapf.readline()) # prints b"Hello Python!\n"
... print(mapf[:5]) # prints b"Hello"
... mapf.tell()
... mapf[6:] = b" world!\n"
... mapf.seek(0)
... print(mapf.readline()) # prints b"Hello world!\n"
... mapf.close()
...
b'Hello Python!\n'
b'Hello'
14
b'Hello world!\n'
精彩评论