我正在使用 Python 读取以下格式的文件:
iter1
iter2
iter3
[n 行内容]
FLAG = value
iter1
iter2
iter3
iter4
iter5
[n 行内容]
FLAG = value
等....
我想搜索 FLAG,读取该值,然后倒退“n”行并读取最终迭代的值。请注意,迭代次数并不总是相同。每个文件中的行数“n”是一致的;但是,这些行可能包含不同数量的字节,因此我无法使用 seek 功能。
我想做这样的事情:
f = open(file)
for i in f:
a = re.search('FLAG')
if a:
print a
spot=f.tell() #mark original spot
f.seek(-n,1) #rewind by n lines
b = re.search('iter')
print b
f.seek(spot) #return to FLAG line, continue to next data set