Untested. Basically, you want to maintain a lifo cache of 'unread' lines. On each read of a line, if there is something in the cache, you take it out of the cache first. If there's nothing in the cache, read a new line from the file. This is rough, but should get you going.
lineCache = []
def pushLine(line):
lineCache.append(line)
def nextLine(f):
while True:
if lineCache:
yield lineCache.pop(0)
line = f.readline()
if not line:
break
yield line
return
f = open('myfile')
for line in nextLine(f):
# if we need to 'unread' the line, call pushLine on it. The next call to nextLine will
# return the that same 'unread' line.
if some_condition_that_warrants_unreading_a_line:
pushLine(line)
continue
# handle line that was read.