python读取txt文件,查找到指定内容,并做出修改

我用了python读取txt文件,r+模式,怎样写才能实现读取查找到指定内容,然后修改此内容,查找自己已经完成,修改不知道该怎么写,求赐教。谢谢

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')


温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-02-01
你可以把txt的修改后的内容给重新写入文件,这样子会覆盖之前的文件
第2个回答  2018-01-29
用replace() 或者 re.sub
第3个回答  2018-01-31
打开文件r 读取内容 关闭文件 正则修改 打开文件w 覆盖写入 关闭文件
第4个回答  2018-01-26

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:
谢谢答案,嘿嘿