Python内存映射文件读写方式代码示例
本篇文章小编给大家分享一下Python内存映射文件读写方式代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
代码如下:
import os import time import mmap filename = 'test.txt' #如果不存在,创建。 if not os.path.exists(filename): open(filename, 'w') print(os.path.isdir(filename)) if os.path.isfile(filename): print(time.ctime(os.path.getctime(filename))) fd = os.open(filename, os.O_RDWR) m = mmap.mmap(fd, 50, access=mmap.ACCESS_WRITE) # 1024字节的文件。 m.seek(2) buf1 = bytes(b'Zhang') m[2:len(buf1)+2] = buf1 buf2 = b'Phil' m.seek(20) # 定位写入的位置。 m.write(buf2) # 写入字节数据。 m.close() fd = os.open(filename, os.O_RDWR) m = mmap.mmap(fd, 50, access=mmap.ACCESS_READ) m.seek(20) buf3 = m.read(len(buf2)) m.close() print(list(buf3))
操作后的test.txt文件内容:
Zhang Phil
PHP之友评论