请大家看一段代码:
yesterday2是我之前上个帖子创建的文件,为了方便大家看清我把本来的代码复制到下面:
coding=utf-8
f=open("yesterday2","r",encoding="utf-8")
f_new=open("yesterday2.bak","w",encoding="utf-8")
for line in f:
if "昨日当我年少轻狂" in line:
line=line.replace("昨日当我年少轻狂","昨日当韦大仙年少轻狂")
f_new.write(line) else: f_new.write(line)
f.close()
f_new.close()当然"r"是读文件的意思,"w"是写入的意思#coding=utf-8
f=open("yesterday2","r",encoding="utf-8")
f_new=open("yesterday2.bak","w",encoding="utf-8")
for line in f:
if "昨日当我年少轻狂" in line:
line=line.replace("昨日当我年少轻狂","昨日当韦大仙年少轻狂")
f_new.write(line)
f.close()
f_new.close()
其实为了减轻代码的繁琐,所以把代码合并后就是上图那样去掉了else当然有时候会忘记源文件而直接写要替换的内容