Memory-mapped file objects behave like both strings and like file
objects. Unlike normal string objects, however, these are mutable. 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. 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.
示例
import re
import mmap
f = open('path/filename', 'r+b')
mf = mmap.mmap(f.fileno(), 0)
mf.seek(0) # reset file cursor
m = re.search('pattern', mf)
print m.start(), m.end()
mf.close()
f.close()
试试这个:
除非打开文件,否则无法在文件中找到文本的位置。这就像让别人看报纸而不睁开眼睛。
回答你问题的第一部分,相对来说比较简单。
您可以使用memory-mapped files和regular expressions。
示例
相关问题 更多 >
编程相关推荐