Python中的内存影射文件

2019-03-27  本文已影响0人  louyang
1. 新建一个文本文件
#!/usr/bin/python3
import mmap

with open("hello.txt", "w") as f:
    f.write("Hello Python\n")
    f.write("Hello programming\n")
$ ./a.py && cat hello.txt
Hello Python
Hello programming
2. 打开一个内存影射文件,并操作
#!/usr/bin/python3
import mmap

with open("hello.txt", "w") as f:
    f.write("Hello Python\n")
    f.write("Hello programming\n")

with open("hello.txt", "r+") as f:
    map = mmap.mmap(f.fileno(), 0)
    print(map[:])
$ ./a.py
b'Hello Python\nHello programming\n'
3. 修改内存,就是修改文件
#!/usr/bin/python3
import mmap

with open("hello.txt", "w") as f:
    f.write("Hello Python\n")
    f.write("Hello programming\n")

with open("hello.txt", "r+") as f:
    map = mmap.mmap(f.fileno(), 0)
    print(map[:])
    map[6:12] = b'World!'
    print(map.readline())
    map.close()
$ ./e.py && cat hello.txt
b'Hello Python\nHello programming\n'
b'Hello World!\n'
Hello World!
Hello programming
参考
  1. https://docs.python.org/3.0/library/mmap.html
上一篇下一篇

猜你喜欢

热点阅读