How to Find String in Text File Python?

By Hardik Savani October 30, 2023 Category : Python

Hello Artisan,

I am going to show you an example of python find string in text file. In this article, we will implement a python find specific string in text file. I explained simply step by step how to find word in text file python. I am going to show you about how to find string in text file python. Alright, let us dive into the steps.

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

Example 1:

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!

I hope it can help you...

Tags :
Shares