You have to remember the position by calling file.tell()
before the readline and then calling file.seek()
to rewind. Something like:
fp = open('myfile')
last_pos = fp.tell()
line = fp.readline()
while line != '':
if line == 'SPECIAL':
fp.seek(last_pos)
other_function(fp)
break
last_pos = fp.tell()
line = fp.readline()
I can't recall if it is safe to call file.seek()
inside of a for line in file
loop so I usually just write out the while
loop. There is probably a much more pythonic way of doing this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…