python標准庫介紹——19 mmap 模塊詳解


==mmap 模塊==


(2.0 新增) ``mmap`` 模塊提供了操作系統內存映射函數的接口, 如 [Example 2-13 #eg-2-13] 所示. 
映射區域的行為和字符串對象類似, 但數據是直接從文件讀取的.

====Example 2-13. 使用 mmap 模塊====[eg-2-13]

```
File: mmap-example-1.py

import mmap
import os

filename = "samples/sample.txt"

file = open(filename, "r+")
size = os.path.getsize(filename)

data = mmap.mmap(file.fileno(), size)

# basics
print data
print len(data), size

# use slicing to read from the file
# 使用切片操作讀取文件
print repr(data[:10]), repr(data[:10])

# or use the standard file interface
# 或使用標准的文件接口
print repr(data.read(10)), repr(data.read(10))

*B*<mmap object at 008A2A10>
302 302
'We will pe' 'We will pe'
'We will pe' 'rhaps even'*b*
```

在 Windows 下, 這個文件必須以既可讀又可寫的模式打開( `r+` , `w+` , 或 `a+` ), 否則 ``mmap`` 調用會失敗. 

``` [!Feather 注: 經本人測試, a+ 模式是完全可以的, 原文只有 r+ 和 w+]

%% WindowsError: [Error 5] Access is denied 一般是這個錯誤 

[Example 2-14 #eg-2-14] 展示了內存映射區域的使用, 在很多地方它都可以替換普通字符串使用, 
包括正則表達式和其他字符串操作.

====Example 2-14. 對映射區域使用字符串方法和正則表達式====[eg-2-14]

```
File: mmap-example-2.py

import mmap
import os, string, re

def mapfile(filename):
    file = open(filename, "r+")
    size = os.path.getsize(filename)
    return mmap.mmap(file.fileno(), size)

data = mapfile("samples/sample.txt")

# search
index = data.find("small")
print index, repr(data[index-5:index+15])

# regular expressions work too!
m = re.search("small", data)
print m.start(), m.group()

*B*43 'only small\015\012modules '
43 small*b*
```

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM