0

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.

6
  • 2
    Do you have any code that you tried? You are going to want to first look into 1) opening the file and 2) using readlines to get all the lines Commented May 25, 2020 at 20:05
  • 2
    Looks like homework. We can help but you need to start yourself first. Look how to read a file, line, split into words. Comment/Edit if you face a difficulty. Commented May 25, 2020 at 20:07
  • I have re-edited my question and show the code. I am struggling with how to print the next three lines. Maybe you guys can give me some ideas? I don't need to print all the lines. Thanks. @CoryNezin Commented May 25, 2020 at 21:03
  • I have added my code. I have no idea about how to print the next three lines after the line the contains the word pending, maybe you can give me some ideas? Thanks. @sc0rp1on Commented May 25, 2020 at 21:06
  • What if another "pending" occurs inside the "next three lines"? Do you ignore it (because you are already printing 3 lines)? Do you restart printing a-new on the count of three? Do you finish printing the original 3 lines and then print another set of 3 for each occurrence of "pending" in the previous line(s)? Commented May 25, 2020 at 21:07

2 Answers 2

1

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 
Sign up to request clarification or add additional context in comments.

Comments

0

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?

3 Comments

Thanks for your answer. Actually, the design of the file is, if the line contains the word 'pending', the next three lines will not contain it anymore
Could you please explain what does 'counter -= 1' mean? I don't get that.
counter -=1 decreases the value of counter by 1 (it is like counter=counter-1)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.