Wie suche und ersetze ich Text in einer Datei mit Python 3?
Hier ist mein Code:
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...' )
Eingabedatei:
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
Wenn ich 'ram' in der obigen Eingabedatei suche und durch 'abcd' ersetze, funktioniert das als Zauber. Aber wenn ich es umgekehrt mache, dh 'abcd' durch 'ram' ersetze, bleiben am Ende einige Junk-Charaktere übrig.
Ersetzen von 'abcd' durch 'ram'
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd