with open('input') as fin, open('output','w') as fout: for line in fin: fout.write(line) if line == 'xxxxxn':next_line = next(fin)if next_line == 'yyyyyn': fout.write('my_linen')fout.write(next_line)
这将插入之间的线路 每 发生
xxxxxn并
yyyyyn在文件中。
另一种方法是编写一个函数以产生行,直到看到一个
xxxxxnyyyyyn
def getlines(fobj,line1,line2): for line in iter(fobj.readline,''): #This is necessary to get `fobj.tell` to work yield line if line == line1: pos = fobj.tell() next_line = next(fobj): fobj.seek(pos) if next_line == line2: return
然后,您可以使用此方法直接传递给
writelines:
with open('input') as fin, open('output','w') as fout: fout.writelines(getlines(fin,'xxxxxn','yyyyyn')) fout.write('my_linen') fout.writelines(fin)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)