【发布时间】:2013-06-13 00:22:06
【问题描述】:
如何使用 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( "> " )
#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
当我在上面的输入文件中搜索并用“abcd”替换“ram”时,它就像一个魅力。但是当我反之亦然,即用“ram”替换“abcd”时,最后会留下一些垃圾字符。
用“ram”替换“abcd”
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
【问题讨论】:
-
你说“最后留下了一些垃圾字符”能不能再具体一点,你看到了什么?
-
用我得到的输出更新了问题。
-
这是实现
map而不是循环的好答案:stackoverflow.com/questions/26986229/…,这就是我所采用的
标签: python python-3.x string file replace