Categories
Python Answers

How to search for a string in text files with Python?

Spread the love

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 open the file and then use the in operator to search for its content.

For instance, we write

with open('example.txt') as f:
    if 'hello' in f.read():
        print("found")

to open the example.txt file with open.

And then we call read to read the file into a string.

Then we check if 'hello' is in the string with in.

Conclusion

To search for a string in text files with Python, we can open the file and then use the in operator to search for its content.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *