Reputation: 15
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
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
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