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

2024-08-19 09:24:19
推荐回答(5个)
回答1:

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


回答2:

你可以把txt的修改后的内容给重新写入文件,这样子会覆盖之前的文件

回答3:

用replace() 或者 re.sub

回答4:

打开文件r 读取内容 关闭文件 正则修改 打开文件w 覆盖写入 关闭文件

回答5:


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