文章目录 [ 隐藏 ]
python读取txt文件,查找到指定内容,并做出修改:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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 as e: print e modifyip('a.txt','a','A') |
函数介绍:
1 |
lines=open(tfile,'r').readlines() |
python的open()方法读取文件内容,readLines,以行的方式读取。
lines=open(tfile,’r’).readlines() 读取tfile文件每一行的内容
1 |
lines[i]=lines[i].replace(sstr,rstr) |
Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max
1 |
open(tfile,'w').writelines(lines) |
python的writelines()方法按行写文件内容,和readLines以行的方式读取相对应open(tfile,’w’).writelines(lines)
未经允许不得转载:Python在线学习 » python读取txt文件,查找到指定内容,并做出修改