1

Hello, so, i'm having trouble to find if text file contains string. for example. and i want to create program to check if this file contains string 'banana'. i have tried this but it didn't work

with open("test.txt","r") as f:
    content = f.read()
    for line in content:
        if 'banana' in line:
            do_something()
        else:
            exit()

text file looks like this:

banana is yellow
apple is red
python is good
Varsima
  • 31
  • 1
  • 6

1 Answers1

4

You don't need looping 'cause your file is just text, so just use conditional

with open("test.txt","r") as f:
    content = f.read()
    if 'banana' in content:
        do_something()
    else:
        exit()
notVitor
  • 66
  • 4