×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Print 4 lines before and after a "match" found

Print 4 lines before and after a "match" found

Print 4 lines before and after a "match" found

(OP)
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.

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

RE: Print 4 lines before and after a "match" found

Hi

The first half of your code is using file.readlines() to slurp the entire file into memory. That allows you to easily access any line, so just change the slice's 2nd value :

CODE --> Python

with open(myfile, "r") as f:
    lines = f.readlines()
    for index, line in enumerate(lines):
        if "FIND" in line:
            print("".join(lines[max(0, index - 4):index + 5])) 

While that is simple and readable, work probably not work fine on bigger files. For those the second half of your code is more suitable, but unfortunately islice() can not handle negative indexes, so you have to handle the before lines yourself :

CODE --> Python

from itertools import islice

before = []
with open(myfile, "r") as f:
    for line in f:
        before.append(line)
        if len(before) > 5:
            before.pop(0)
        if "FIND" in line:
            print("".join(before) + "".join(islice(f, 4))) 

The above is the simplified version, but all those list.pop() will slow it down, so you better avoid it :

CODE --> Python

from itertools import islice

before = []
before_index = 0
with open(myfile, "r") as f:
    for line in f:
        if (len(before) < 5):
            before.append(line)
        else:
            before[before_index] = line
            before_index += 1
            if before_index > len(before) - 1:
                before_index = 0
        if "FIND" in line:
            print("".join(before[before_index:]) + "".join(before[:before_index]) + "".join(islice(f, 4))) 

Just for completeness, there would be another way using islice(), but due to its inability to handle negative indexes, we rewind the file, so this one does not handle multiple matches :

CODE --> Python

from itertools import islice

index = 0
with open(myfile, "r") as f:
    for line in f:
        index += 1
        if "FIND" in line:
            f.seek(0)
            print("".join(islice(f, index - 5, index + 4)))
            break 

Feherke.
feherke.github.io

RE: Print 4 lines before and after a "match" found

(OP)
That is awesome!
Now I need to understand it. Thank you for your coaching!

RE: Print 4 lines before and after a "match" found

(OP)

To "feherke".

I'm trying to understand your code but it is too much for me for now.
Why this If block is the last block in the script?

CODE --> python

if "FIND" in line: 
And this part of the script is totally confusing

CODE --> python

if (len(before) < 5):
            before.append(line)
        else:
            before[before_index] = line
            before_index += 1 

CODE --> Python

from itertools import islice

before = []
before_index = 0
with open(myfile, "r") as f:
    for line in f:
        if (len(before) < 5):
            before.append(line)
        else:
            before[before_index] = line
            before_index += 1
            if before_index > len(before) - 1:
                before_index = 0
        if "FIND" in line:
            print("".join(before[before_index:]) + "".join(before[:before_index]) + "".join(islice(f, 4))) 

Also, I cannot print lines "before" and lines "after" to a file.
Could you help me please?
Thank you.



RE: Print 4 lines before and after a "match" found

(OP)
And the same story with this snippet.
It prints what I need but I need to print it to aa different file.
Have no idea how to print the lines to a file.

CODE --> python

index = 0
with open(myfile, "r") as f:
    for line in f:
        index += 1
        if "FIND" in line:
            f.seek(0)
            print("".join(islice(f, index - 5, index + 4)))
            
            break 

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close