Python read specific lines of text between two strings

时光怂恿深爱的人放手 提交于 2019-11-29 05:02:16

One slight modification which looks like it should cover your problem:

flist = open("filename.txt").readlines()

parsing = False
for line in flist:
    if line.startswith("\t**** Report 1"):
        parsing = True
    elif line.startswith("\t**** Report 2"):
        parsing = False
    if parsing:
        #Do stuff with data 

If you want to avoid parsing the line "* Report 1"... itself, simply put the start condition after the if parsing, i.e.

flist = open("filename.txt").readlines()

parsing = False
for line in flist:

    if line.startswith("\t**** Report 2"):
        parsing = False
    if parsing:
        #Do stuff with data 
    if line.startswith("\t**** Report 1"):
        parsing = True

Here is possible alternative using the itertools module.
Although here the question requires checking for [key], I'm adding also itertool.islice() to show that it is possible to skip few lines after the start-reading marker when the user has some prior information.

from itertools import takewhile, islice, dropwhile

with open('filename.txt') as fid:
    for l in takewhile(lambda x: '***** REPORT 2 *****' not in x, islice(dropwhile(lambda x: '***** REPORT 1 *****' not in x, fid), 1, None)):
        if not '[key]' in l:
            continue
        print(l)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!