Search code examples
pythontextcontains

how to check if text file contains string?


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

Solution

  • 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()