Python-如何搜索和替换文件中的文本?
如何使用Python 3搜索和替换文件中的文本?
这是我的代码:
import osimport 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 abcdThis is dummy text file.
This is how search and replace works abcd
当我在上面的输入文件中搜索并将“ ram”替换为“ abcd”时,它起了一种魅力。但是,反之亦然,即用“ ram”替换“ abcd”时,一些垃圾字符会保留在末尾。
用“ ram”代替“ abcd”
hi this is ram hi this is ramThis is dummy text file.
This is how search and replace works rambcd
回答:
fileinput已经支持就地编辑。stdout在这种情况下,它将重定向到文件:
#!/usr/bin/env python3import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')
以上是 Python-如何搜索和替换文件中的文本? 的全部内容, 来源链接: utcz.com/qa/431953.html