简体   繁体   中英

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM