I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory
if you remove the indent at the like below, it will search and replace in multiple line. See below for example.
def replace(file, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    print fh, abs_path
    new_file = open(abs_path,'w')
    old_file = open(file)
    for line in old_file:
        new_file.write(line.replace(pattern, subst))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file)
    #Move new file
    move(abs_path, file)