Python 中的内存映射文件支持 (mmap)?


当您将文件对象读取到 Python 程序中并想要修改时,可以通过两种方式完成。第一种方法是修改文件所在的物理存储驱动器中的内容,第二种方法是直接在系统的内存或 RAM 中修改它。在本文中,我们将了解如何使用 Python 中可用的 mmap 模块读取、搜索和修改文件对象的内容。内存映射无需进行诸如 open、read 和 lseek 等系统调用来操作文件,而是将文件的数据放入内存中,允许您直接在内存中操作文件。

读取内存映射文件

在下面的示例中,我们将整个文件一次性读取到内存中,并将其作为文件对象保存在内存中。然后,我们以读取模式访问它。最后,如您所见,整个文件表示一个对象,我们从中切片某些位置以获取所需的文本。

示例

import mmap

def read_mmap(fname):
   with open(fname, mode="r", encoding="utf8") as fobj:
      with mmap.mmap(fobj.fileno(), length=0, access=mmap.ACCESS_READ) as mmap_obj:
         print(mmap_obj[4:26])

read_mmap('E:\test.txt')

输出

运行以上代码将得到以下结果:

'emissions from gaseous'

使用 mmap 查找

示例

import mmap
import time

def regular_io_find(fname):
   with open(fname, mode="r", encoding="utf-8") as fobj:
      text = fobj.read()
      text.find("Death ")

def mmap_io_find(fname):
   with open(fname, mode="r", encoding="utf-8") as fobj:
      with mmap.mmap(fobj.fileno(), length=0, access=mmap.ACCESS_READ) as mmap_obj:
         mmap_obj.find(b"Death ")

start_time_r = time.time()
regular_io_find('E:\emissions.txt')
end_time_r = time.time()
print("Regualr read start time :",start_time_r)
print("Regualr read start time :",end_time_r)
print('Regular read time : {0}'.format(end_time_r - start_time_r))

start_time_m = time.time()
mmap_io_find('E:\emissions.txt')
end_time_m = time.time()
print("mmap read start time :",start_time_m)
print("mmap read start time :",end_time_m)
print('mmap read time : {0}'.format(end_time_m - start_time_m))

输出

运行以上代码将得到以下结果:

2013
Regualr read start time : 1609812463.2718163
Regualr read end time : 1609812463.2783241
Regular read time to find: 0.00650787353515625
mmap read start time : 1609812463.2783241
mmap read start time : 1609812463.2783241
mmap read time to find : 0.0

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

写入文件

在下面的示例中,我们获取一个文件并使用 mmap 模块以 r+ 访问代码打开它,这允许同时读取和写入文件。创建文件对象后,我们通过切片选择一个位置,可以在该位置写入字符串。

示例

import mmap

def mmap_io_write(fname):
   with open(fname, mode="r+") as fobj:
      with mmap.mmap(fobj.fileno(), length=0, access=mmap.ACCESS_WRITE) as mmap_obj:
         mmap_obj[20:26] = b"Hello!"
         mmap_obj.flush()

mmap_io_write('E:\emissions.txt')

运行以上代码后,我们可以打开文件并查看字符串 Hello! 已写入文件从第 20 个字节到第 26 个字节的位置。

更新于: 2021年1月12日

1K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告