¿Cómo buscar y reemplazar texto en un archivo usando Python?

¿Cómo busco y sustituyo texto en un archivo utilizando Python 3?

Aquí está mi código:

import os
import sys
import fileinput

print ("Text to search for:")
textToSearch = input( "> " ) 

print ("Text to replace it with:")
textToReplace = input( "> " )

print ("File to perform Search-Replace on:")
fileToSearch  = input( "> " )
#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()


input( '\n\n Press Enter to exit...' )

Fichero de entrada:

hola esto es abcd hola esto es abcd

Este es un archivo de texto ficticio.

Así es como funciona la búsqueda y reemplazo abcd.

Cuando busco y sustituyo 'ram' por 'abcd' en el archivo de entrada anterior, funciona como un hechizo. Pero cuando lo hago viceversa, es decir, al reemplazar 'abcd' por 'ram', algunos caracteres no deseados se dejan al final.

Sustituyendo 'abcd' por 'ram'

hola esto es ram hola esto es ram

Este es un archivo de texto ficticio.

Así es como funciona la búsqueda y reemplazo.

Respuestas a la pregunta(12)

Su respuesta a la pregunta