Skip to content

All topics  /  Python

How to Find Text File String in Python?

Python ·

Hi Dev,

Today our leading topic is how to find strings in a text file in Python. I would like to share with you Python find string in a text file. We will look at an example of Python finding a specific string in a text file. if you have question about how to find words in a text file Python then I will give a simple example with a solution

If you are looking to find a string in a text file using a Python program. then there are lots of ways to do this. Here, I will give you a very simple example to search for text in a file python. we will create an example.txt with some dummy text. we will find the "Solution" string from that text file. you can see the following code here:

Example :


Here, we will create "example.txt" file as like the below:

example.txt

This is ItSolutionStuff.com
demo

Now, we will create main.py file and find string from that file as like the below code:

main.py

findString = "Solution"

  
with open('example.txt') as f:
    if findString in f.read():
        print("Found!")

Output:

Found!