How to check if a string exists in a file in Python?


I want to search the given word in a file, if it exists I need to print yes else no. How can I do that?

1 Answer

4 years ago by

Try below code,

with open('file.txt') as f:
     if 'hello' in f.read():
         print('Yes')
    else:
         print('No')
4 years ago by Divya