mmap regex search replace

David Pratt fairwinds.dp at gmail.com
Fri Apr 3 08:46:14 EDT 2009


Hi. I have a circumstance where I have to search and replace a block  
of text in a very large file. I have written some psuedo code to  
locate the text and print the span of text to be removed and replaced  
by new block. Can someone advise what to do to remove the text span  
and insert with the new text. the match.span() provides a tuple of the  
starting and ending position. Many thanks.

Regards,
David


import mmap
import re

text_to_insert = 'the block to insert'

pattern = re.compile(my regex here)

f = open('my_large_file.dat', 'r+')
try:
	m = mmap.mmap(f.fileno(), 0)
	try:
		match = chart_re.search(m)
		print match.span()
	finally:
		m.close()
finally:
	f.close()





More information about the Python-list mailing list