with open('example.txt') as f: if 'blabla' in f.read(): print("true")
Here is what the above code is Doing:
1. It opens the file example.txt and assigns the file object to the variable f.
2. It reads the contents of the file into a string and checks if the string contains the word ‘blabla’.
3. If the word ‘blabla’ is in the string, it prints ‘true’.
The code above is a bit long and complicated. We can simplify it by using the in operator.
The in operator checks if a value is in a sequence. If the value is in the sequence, the in operator returns True. Otherwise, it returns False.
Here’s how we can use the in operator to check if a word is in a file: