美文网首页
Python中的内存影射文件

Python中的内存影射文件

作者: louyang | 来源:发表于2019-03-27 17:15 被阅读0次
    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

    相关文章

      网友评论

          本文标题:Python中的内存影射文件

          本文链接:https://www.haomeiwen.com/subject/trozvqtx.html