6.9.2 写文件
要建立内存映射文件来接收更新,映射之前首先要使用模式’r+’(而不是’w’)打开文件以便完成追加。然后可以使用任何改变数据的API方法(例如write()或赋值到一个分片等)。
下面的例子使用了默认访问模式ACCESS_WRITE,并赋值到一个分片,以原地修改某一行的一部分。
import mmap
import shutil
# Copy the example file.
shutil.copyfile('lorem.txt','lorem_copy.txt')
word = b'consectetuer'
reversed = word[::-1]
print('Looking for :',word)
print('Replacing with :',reversed)
with open('lorem_copy.txt','r+') as f:
with mmap.mmap(f.fileno(),0) as m:
print('Before:\n{}'.format(m.readline().rstrip()))
m.seek(0) # Rewind
loc = m.find(word)
m[loc:loc + len(word)] = reversed
m.flush()
m.seek(0) # Rewind
print('After :\n{}'.format(m.readline().rstrip()))
f.seek(0) # Rewind
print('File :\n{}'.format(f.readline().rstrip()))
内存和文件中第一行中间的单词“consectetuer”将被替换。
运行结果:
复制模式
使用访问设置ACCESS_COPY时不会把修改写入磁盘上的文件。
import mmap
import shutil
# Copy the example file.
shutil.copyfile('lorem.txt','lorem_copy.txt')
word = b'consectetuer'
reversed = word[::-1]
with open('lorem.txt','r+') as f:
with mmap.mmap(f.fileno(),0,access=mmap.ACCESS_COPY) as m:
print('Memory Before:\n{}'.format(m.readline().rstrip()))
print('File Before :\n{}\n'.format(f.readline().rstrip()))
m.seek(0) # Rewind
loc = m.find(word)
m[loc:loc + len(word)] = reversed
m.seek(0) # Rewind
print('Memory After :\n{}'.format(m.readline().rstrip()))
f.seek(0)
print('File After :\n{}'.format(f.readline().rstrip()))
在这个例子中,必须单独地回转文件句柄和mmap句柄,因为这两个对象的内部状态会单独维护。
运行结果: