每次到达开始标记直到停止都可以使用itertools.take:
from itertools import takewhilewith open("myFile.txt") as f: array = [] for line in f: if line.startswith('start flag'): data = takewhile(lambda x: not x.startswith("stop flag"),f) # use data and repeat
或者只是使用一个内循环:
with open("myFile.txt") as f: array = [] for line in f: if line.startswith('start flag'): # beginning of section use first lin for line in f: # check for end of section breaking if we find the stop lone if line.startswith("stop flag"): break # else process lines from section
文件对象返回其自己的迭代器,因此当您遍历时
f,指针将继续移动,当您到达start标志时,开始处理一段,直到您到达停靠点为止。根本没有理由重新打开文件,只需在文件的各行中迭代一次即可使用这些部分。如果开始和停止标志线被认为是该部分的一部分,请确保也使用它们。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)