在工作中,有可能有一些场景,例如我要替换我txt文档中,所有行中包含test文字的的行内容,例如我们可以替换为空,或者某一个特定字符串呢?不多说,上代码。。
def repalceString():
lineList = []
file = open('mytest.txt','r')
for (num,value) in enumerate(file):
if "test" in value:
lineList.append(num)
file.close()
fileRead = open('mytest.txt','r')
newFile = open("newTest.txt","w")
for (num,value) in enumerate(fileRead):
if num in lineList:
lineContent = value.replace(value,'myceshi')
newFile.write(lineContent)
else:
newFile.write(value)
fileRead.close()
newFile.close()
if __name__ == "__main__":
repalceString()