Python Forum
Need print out lines before and after the match
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need print out lines before and after the match
#1
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.

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  ###
Reply


Messages In This Thread
Need print out lines before and after the match - by tester_V - Aug-10-2020, 12:44 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Print the next 3 lines knob 3 384 May-22-2024, 12:26 PM
Last Post: andraee
  failing to print not matched lines from second file tester_V 14 6,553 Apr-05-2022, 11:56 AM
Last Post: codinglearner
  If match not found print last line tester_V 2 3,025 Apr-26-2021, 05:18 AM
Last Post: tester_V
  why print('\n') produced 2 new lines instead of 1 - Located inside a FOR loop JulyFire 2 2,701 Jan-10-2021, 01:50 AM
Last Post: JulyFire
  Iterate 2 large text files across lines and replace lines in second file medatib531 13 6,376 Aug-10-2020, 11:01 PM
Last Post: medatib531
  Look for match in two files and print out in the first file Batistuta 0 1,682 Mar-03-2020, 02:27 PM
Last Post: Batistuta
  print python json dump onto multiple lines lhailey 2 20,408 Mar-02-2020, 12:47 PM
Last Post: vishalhule
  Read serial BR=9600 . print me 2 lines? korenron 1 2,373 Dec-31-2019, 06:39 PM
Last Post: DeaD_EyE
  using vars from one file to match lines in another gt76_noobster 3 2,753 Jan-30-2019, 05:34 PM
Last Post: ichabod801
  Print multiple record lines ntigner 3 3,566 Feb-08-2018, 05:34 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020