Come posso cercare e sostituire il testo in un file usando Python 3?
Ecco il mio codice:
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...' )
File di input:
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
Quando cerco e sostituisco 'ram' con 'abcd' nel file di input sopra, funziona come un incantesimo. Ma quando lo faccio viceversa, ovvero sostituendo "abcd" con "ram", alcuni personaggi spazzatura vengono lasciati alla fine.
Sostituzione di 'abcd' con 'ram'
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd