mmap —— 一个优化“文件 str 文件”流程的类 - Serbipunk/notes GitHub Wiki
https://docs.python.org/2/library/mmap.html
Memory-mapped file objects behave like both strings and like file objects.
内存映射文件(mmap)类型,具有str对象和其他文件对象的特性
Unlike normal string objects, however, these are mutable.
不像str对象的一点是,他们是可修改的。
You can use mmap objects in most places where strings are expected; for example, you can use the re module to search through a memory-mapped file.
大部分情况,mmap对象可以替换str对象,例如,你可以用re
去搜索mmap文件
Since they’re mutable, you can change a single character by doing obj[index] = 'a', or change a substring by assigning to a slice: obj[i1:i2] = '...'.
由于他们是可变的,你可以通过索引及切片操作直接改变对象
You can also read and write data starting at the current file position, and seek() through the file to different positions.
也可以使用seek()
做地址偏移操作
A memory-mapped file is created by the mmap constructor, which is different on Unix and on Windows.
mmap文件由mmap类进行初始化。然而mmap在unix和windows系统是2个实现。
In either case you must provide a file descriptor for a file opened for update.
这2种情况下,你都得提供一个文件描述符,指向一个文件以待更新…………(听起来非常重型,要操作文件!)
If you wish to map an existing Python file object, use its fileno() method to obtain the correct value for the fileno parameter.
如果你想重用一个打开的python文件对象,使用fileno()
,鼓捣好正确的参数
Otherwise, you can open the file using the os.open() function, which returns a file descriptor directly (the file still needs to be closed when done).
否则,需要使用os.open
函数。
import mmap
# write a simple example file
with open("hello.txt", "wb") as f:
f.write("Hello Python!\n")
with open("hello.txt", "r+b") as f:
# memory-map the file, size 0 means whole file
mm = mmap.mmap(f.fileno(), 0)
# read content via standard file methods
print mm.readline() # prints "Hello Python!"
# read content via slice notation
print mm[:5] # prints "Hello"
# update content using slice notation;
# note that new content must have same size
mm[6:] = " world!\n"
# ... and read again using standard file methods
mm.seek(0)
print mm.readline() # prints "Hello world!"
# close the map
mm.close()