如何使用python3搜索和替换文件中的文本?
这是我的代码:
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...' )
输入文件:
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