如果您想要一个所需行的列表,那么创建一个空列表并添加每个相关行
with open("test.txt") as f:
reslist = []
for line in f:
if line.startswith('[header1]'): # beginning of section use first line
for line in f: # check for end of section breaking if we find the stop line
if line.startswith("[header2]"):
break
else: # else process lines from section
print(line.rstrip("\n"))
reslist.append(line)
return reslist
如果你想输出一个字符串,你可以。。。
resstring = '\n'.join(reslist)
如果您想收集dict中每个标题的输出,请参阅上面的“DarkKnight”评论