Skip to content Skip to sidebar Skip to footer

Python How To Grab Certain Number Of Lines After Match

Let's say I have an input text file of the following format: Section1 Heading Number of lines: n1 Line 1 Line 2 ... Line n1 Maybe some irrelevant lines Section2 Heading Numb

Solution 1:

# f is a file object
# n1 is how many lines to read
lines = [f.readline() for i in range(n1)]

Solution 2:

You can put logic like this in a generator:

def take(seq, n):
    """ gets n items from a sequence """
    return [next(seq) for i in range(n)]

def getblocks(lines):
    # `it` is a iterator and knows where we are in the list of lines.
    it = iter(lines)
    for line in it:
        try:
            # try to find the header:
            sec, heading, num = line.split()
            num = int(num)
        except ValueError:
            # didnt work, try the next line
            continue

        # we got a header, so take the next lines
        yield take(it, num) 

#test
data = """
Section1 Heading  3
Line 1
Line 2
Line 3

Maybe some irrelevant lines

Section2 Heading 2
Line 1
Line 2
""".splitlines()

print list(getblocks(data))

Post a Comment for "Python How To Grab Certain Number Of Lines After Match"