Python read specific lines of text between two strings

前端 未结 2 694
轮回少年
轮回少年 2020-12-17 05:24

I am having trouble getting python to read specific lines. What i\'m working on is something like this:

lines of data not needed
lines of data not needed
lin         


        
相关标签:
2条回答
  • 2020-12-17 05:48

    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
    
    0 讨论(0)
  • 2020-12-17 05:53

    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)
    
    0 讨论(0)
提交回复
热议问题