def modifyip(tfile,sstr,rstr):
try:
lines=open(tfile,'r').readlines()
flen=len(lines)-1
for i in range(flen):
if sstr in lines[i]:
lines[i]=lines[i].replace(sstr,rstr)
open(tfile,'w').writelines(lines)
except Exception,e:
print e
modifyip('a.txt','a','A')
你可以把txt的修改后的内容给重新写入文件,这样子会覆盖之前的文件
用replace() 或者 re.sub
打开文件r 读取内容 关闭文件 正则修改 打开文件w 覆盖写入 关闭文件
把
flen=len(lines)-1
for i in range(flen):
改成:
for i in range(0,len(lines)): #才生效
ptyhon3.5不支持:except Exception,e: 改成 except Exception as e:
谢谢答案,嘿嘿