Hugo
Hugo

Reputation: 15

How to print next three lines?

I have a large file with following format:

Good day, Jenny. (pending)
Good day, Tommy.
Good day, Henry.
Good day, Mary.
Good day, Austin.
Good day, Eason.(pending)
Good day, Eric.
.....

What I need to do is to print the line that contains the word 'pending' and its following three lines. However, I just know how to print the line that contains the word 'pending'. Some one can help? Here is my simple code:

word = 'pending'
with open ('1.txt', 'r') as inf:
    for line in inf.readlines():
        #line = line.split()
        if word in line:
            print(line)

Thanks for your help.

Upvotes: 0

Views: 110

Answers (2)

CarlosSR
CarlosSR

Reputation: 1195

You need some kind of variable that indicates whether you have found a 'word' in line.

counter=0
word = 'pending'
with open ('1.txt', 'r') as inf:
    for line in inf.readlines():
        if counter>0:
            print(line)
        counter-=1
        #line = line.split()
        if word in line:
            counter=3

Also, what are you expecting if one of the next 3 lines has a pending?

Upvotes: 0

Georgina Skibinski
Georgina Skibinski

Reputation: 13407

Almost there:

word = 'pending'
i=0
with open ('1.txt', 'r') as inf:
    for line in inf.readlines():
        if (word in line):
            print(line)
            i=1
        if(i>=1) and (i<4):
            print(line)
            i+=1

Upvotes: 1

Related Questions