您可以使用itertools.dropwhile 删除行,直到到达您想要的行,然后循环直到找到以# 开头的行
from itertools import dropwhile
def section(fle, start, stop):
with open(fle) as f:
# consume lines until we get to our start line
drop = dropwhile(lambda x: x.strip() != start, f)
# skip start
next(drop, "")
# loop starting at line after start line
for line in drop:
# if we reach stop line break
if line.startswith(stop):
break
# else we just yield the line
yield line.rstrip()
输出:
In [4]: list(section("in.txt", "#923", "#"))
Out[4]: ['*21', '*23', '*56', '*1', '*3']
适用于从 start 开始并由以 # 开头的行分隔的多个部分:
from itertools import dropwhile, groupby
def section(fle, start, end):
with open(fle) as f:
grps = groupby(dropwhile(lambda x: x.strip() != start, f),
key=lambda x: x.startswith(end))
for k, v in grps:
if not k:
yield list(map(str.strip,v))
演示:
n [13]: cat in.txt
(4.471719725275173E-003,2.163649191486555E-002)
(6.471719725275173E-003,2#123
*21
*23
*56
*1
*3
#923
*21
*23
*56
*1
*3
#165.163649191486555E-002)
*210
*230
*560
*10
*30
#165.163649191486555E-002)
In [14]: list(section("in.txt", "#923", "#"))
Out[14]: [['*21', '*23', '*56', '*1', '*3'], ['*210', '*230', '*560', '*10', '*30']]