Sometimes, we want to search for a string in text files with Python.
In this article, we’ll look at how to search for a string in text files with Python.
How to search for a string in text files with Python?
To search for a string in text files with Python, we can use the in operator.
For instance, if we have the following text file:
example.txt
blablabla
Then we write:
with open('example.txt') as f:
if 'blabla' in f.read():
print("true")
We call open with the path of the text file to open.
Then we call f.read to read the file’s contents into a string.
And then we use the in operator to check if the text we’re looking for is in the string returned by read.
Since this is True, we see 'true' printed.
Conclusion
To search for a string in text files with Python, we can use the in operator.