Как выполнить поиск и заменить текст в файле с помощью Python 3?
Вот мой код:
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("> ")
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...')
Входной файл:
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
Когда я ищу и заменяю «ram» на «abcd» во входном файле выше, это работает как шарм. Но когда я делаю наоборот, то есть заменяю «abcd» на «ram», в конце остаются некоторые ненужные символы.
Замена «abcd» на «ram»:
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd