Home > Software design >  How can I search a file I open and check to see if user's input is located inside? Then print t
How can I search a file I open and check to see if user's input is located inside? Then print t

Time:07-26

enter image description here

Here is an example of the code I have. The code is saved in the file as:

pizza

100

100

100

I want the user to input the word 'pizza' and I want the program to search the file and print the next 3 elements.

CodePudding user response:

Make sure you have the file food.txt in your directory (name can be changed)

def file_search(food, file="food.txt"):
    count = 0
    with open(file) as f:
        for line in f:
            if count >= 3:
                break

            if line.strip() == food or count:
                print(line.strip())
                count  = 1


file_search(input("Food --> "))
  • Related