使用python替换多行代码

时间:2016-09-08 18:29:03

标签: python

我正在尝试使用python替换HTML文件中的某些行。

#! /usr/local/bin/python
import os,sys,string,filecmp,shutil,stat,pwd,datetime,time,copy,glob,re,getpass,commands
sys.path.insert(0,os.path.join(os.environ['ADM_TOOLS'],'llib'))
import tooldets,CSrcPrj,comnfuncs,COraConnect

patchHtmlName = 'patchmaintenance.html'
f = open (patchHtmlName, "rt")
g = open ('file3.txt', "rt")
h = open ('file4.txt', "rt")
contents = f.read()
contents1 = g.read()
contents2 = h.read()

#" ".join(contents1.split())
newJSCode = contents.replace(contents1, contents2)

fp2 = open(patchHtmlName, "w")
fp2.write(newJSCode)
fp2.close()

虽然File3的代码是:

}

 function fnIsValidEmailId(str)

And the code for File4 is : 

                document.getElementById("beforePage").style.display = "none";
            document.getElementById("afterPage").style.display = "block";
}
 function fnIsValidEmailId(str)

我想将file3的代码替换为file4。

如果我试图将file3的内容替换为单行而不是多行,那么代码可以正常工作并替换它。

执行脚本时,它不会出现任何错误,但不会显示所需的输出。

请帮忙

1 个答案:

答案 0 :(得分:0)

试试这个

import re
...
...
newJSCode = re.sub(r'.*%s'%contents1, contents2, contents, re.DOTALL) 

这将用内容中的contents2替换contents1。我不确定我是否不知道哪一个要被替换,但无论如何你想要相反的只是将contents1更改为contents2,反之亦然