我正在寻找一种替换文件中字符串的通用方法。
我有一个文件(可以是 .txt
、 .bat
、 .xml
)
我想替换特定的字符串,例如"ABC"
,通过另一个字符串,例如"EFG"
我已经尝试过这个:
def replace_in_file(file):
s = open(file).read()
s = s.replace("ABC" ,"EFG")
f = open(file,'w')
f.write(s)
f.close()
我也尝试过这个:
def replace_in_file(file):
with fileinput.FileInput(file) as file:
for line in file:
line.replace("ABC" , "EFG")
但是没有一个不起作用!
我想自动化以下过程:说明
Open file with notepad++
Press ctrl+f
go to replace
and replace "ABC" by "EFG"
最佳答案
我认为在文件中你不能直接替换,所以你也必须写入。否则变更数据将不存在。因此,您还可以创建一个临时文件并在其中写入,或者您可以更改原始文件。所以你的两个函数都是正确的,只需添加类似的东西..
tempFile = open( fileToSearch, 'r+' )
for line in fileinput.input( fileToSearch ):
tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()
关于python - 文件中的通用字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57168038/