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
#2
Why don't you just join lines[index-4] to lines[index+4]? I do not understand why you reopen the file.
Reply
#3
I do not know what that means "Why don't you just join lines[index-4] to lines[index+4]?"
Line ("".join(lines[max(0,index-4):index])) works fine.
It is 4 lines after a "match' Im having problem with.

I tried adding one more print statement but it does not print anything

            print("".join(lines[max(0,index-4):index]))  # print 4 lines preceeding it
            print("".join(lines[max(0,index+4):index]))  # print 4 lines after it
thank you.
Reply
#4
Any ideas how to do this?

Thank you.
Reply
#5
print("".join(lines[max(0,index-4):min(index+4, len(lines)-1)]))
Reply
#6
I underatand it is simple for you deanhystad but it looks amazing to me!
Thank you for your help!
Do you think you could elaborate what this part means and why I have it in the code "len(lines)-1"?
Again, thanks man!
Reply
#7
It looks simple because it is simple. You are doing this:
Quote:Find the letter d and return d, the letter before and the letter after.
0 a
1 b
[2 c
3 d
4 e]
5 f
6 g
Answer: [2:5]
That is simple.

When you are programming, how do you start? Do you write a detailed description of the problem you are trying to solve? I do. Even for simple programs like this. Writing down the problem description places it clearly in my mind. If I don't write down the problem description I may end up solving the wrong problem.

The next thing I do is draw pictures of the problem and my solution. Everyone is a visual thinker and everyone will benefit from drawing. I always write the program on paper first. I fill notebooks with problem descriptions and notes and drawings and pseudocode. If you had drawn a picture of your solution with a short list and maybe some index values I bet you wouldn't have had any trouble writing the code. You are trying to do you designing with Python. You are not comfortable with Python and that makes it a terrible tool for doing design.

My simple drawing above makes me realize there is a bug in my solution. Looking at it now I see the end of the slice was off. If you want the four before and the four after the slice should be lines[max(0,index-4):min(index+5, len(lines))] If index was 4 we would want lines 0 through 8. To get those lines the slice should be 0 to 9 where line[9] is not part of the slice.

max(index+5, len(lines)) does the same thing you were doing with max(0,index-4) except for the end. Thinking some more about it I don't think the min is required. If you ask for a slice that extends beyond the source, the slice is "sliced" to fit.
x = [0, 1, 2]
print(x[0:10])
Output:
[1, 2, 3]
The same is not true if you specify a negative value for the start of slice.
print(x[-2, 3])
Output:
[2, 3]
The same as x[3-2, 3]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  failing to print not matched lines from second file tester_V 14 5,946 Apr-05-2022, 11:56 AM
Last Post: codinglearner
  If match not found print last line tester_V 2 2,845 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,466 Jan-10-2021, 01:50 AM
Last Post: JulyFire
  Iterate 2 large text files across lines and replace lines in second file medatib531 13 5,706 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,558 Mar-03-2020, 02:27 PM
Last Post: Batistuta
  print python json dump onto multiple lines lhailey 2 19,651 Mar-02-2020, 12:47 PM
Last Post: vishalhule
  Read serial BR=9600 . print me 2 lines? korenron 1 2,235 Dec-31-2019, 06:39 PM
Last Post: DeaD_EyE
  using vars from one file to match lines in another gt76_noobster 3 2,573 Jan-30-2019, 05:34 PM
Last Post: ichabod801
  Print multiple record lines ntigner 3 3,389 Feb-08-2018, 05:34 PM
Last Post: nilamo
  Only one of two lines print/syntax error naysjp 2 3,685 Jan-12-2017, 07:08 AM
Last Post: wavic

Forum Jump:

User Panel Messages

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