Zoro99
Zoro99

Reputation: 185

Copy few lines before and after the match string in python

I am new to python and trying to write a script for copying 5 lines before and 5 after the matching string is found

import re

text_file = open(input("Input-file name : ") , "r")
fi =  text_file.readlines()

test = re.compile(r'matching character')

for i in range (len(fi)):
    if test.search(fi[i]):
        print(fi[max(0, i-5)])
        print(fi[max(0, i-4)])
        print(fi[max(0, i-3)])
        print(fi[max(0, i-2)])
        print(fi[max(0, i-1)])
        print(fi[max(0, i-0)])
        print(fi[max(0, i+1)])
        print(fi[max(0, i+2)])
        print(fi[max(0, i+3)])
        print(fi[max(0, i+4)])

Is there a better way than adding multiple print statements to get the output in one command.

Upvotes: 1

Views: 1101

Answers (1)

ekhumoro
ekhumoro

Reputation: 120588

Assuming that the matched line is included in the 5 lines "after", then:

    block = fi[max(0, i - 5): min(len(fi), i + 5)]

will give you a list of the lines. To print the list as one block, you can do:

    print(''.join(block))

Upvotes: 1

Related Questions