for files in filepath: with open(files, 'r') as f: for line in f: if 'Abstract' in line: for line in f: # now you are at the lines you want # do work
文件对象是其自己的迭代器,因此当到达其中的行时,
'Abstract'我们将从该行继续进行迭代,直到消耗完迭代器为止。
一个简单的例子:
gen = (n for n in xrange(8))for x in gen: if x == 3: print('Starting second loop') for x in gen: print('In second loop', x) else: print('In first loop', x)
产生:
In first loop 0In first loop 1In first loop 2Starting second loopIn second loop 4In second loop 5In second loop 6In second loop 7
您还可以使用itertools.dropwhile来消耗所需的行:
from itertools import dropwhilefor files in filepath: with open(files, 'r') as f: dropped = dropwhile(lambda _line: 'Abstract' not in _line, f) next(dropped, '') for line in dropped: print(line)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)