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

2025-03-04 18:31:20
推荐回答(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:
谢谢答案,嘿嘿