Greeting!
I’m trying to print 4 lines before and after a “match” found in a line.
I do not understand how to do it with my current knowledge of Python Confused but I found 2 snippets,
One finds lines Before the match and one After the match. Need help putting them together.
Thank you.
I’m trying to print 4 lines before and after a “match” found in a line.
I do not understand how to do it with my current knowledge of Python Confused but I found 2 snippets,
One finds lines Before the match and one After the match. Need help putting them together.
Thank you.
Python:
from itertools import islice
with open(myfile, "r") as f:
lines = f.readlines()
for index, line in enumerate(lines):
if "FIND" in line:
# print(line.rstrip())
print("".join(lines[max(0,index-4):index])) # print 4 lines preceeding it
with open(myfile, "r") as f:
for line in f:
#print (line)
if "FIND" in line:
#print (line)
#print("".join(line))
print ("".join(islice(f,4))) ### 4 Lines after match ###