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

In this article, we are going to see how to search for a particular string in a text file. 

Ex:- We have a text file and we want to search a particular string from that file with different methods.

Consider we have text file with some text bellow:- 

"This is Codin India.  A Coding Platform for programmers
  You can learn programming from this portal 
 We are expert in Python and every day we come with tips and tricks 
 This Channel is owned by Digamber Jha 
"

 We can see different method one by one. Lets start with first method.

Method 1:- 

First We will just find the string is present in the file or not. If the string found then we will print the output.

Steps for searching:-

  1. Open a file.
  2. Read the file and store it in a variable.
  3. Check the condition using If statement.
  4. If the condition is true print "String found" else "String not found".
  5. Close the file.


Output:-


This is simple method for finding the string or text from file but has some limitations.

Limitations:- 1. It doesn't tell in which line our string found.      

Note:-  So, from the above code and method, we have the result. But if the string found, there is difficulty to find the string where it. In that situation we have to read the whole file to search. 


Method 2:- 

So, to overcome the upper method's limitations, we find the way by printing the line at which our string found. By doing this we will get the line at which line our string found. So that, we don't have to read the whole file.  Read below to learn how we did it:-

We are going to search string line by line. If the string found then we will print that string and line number.

Steps for searching:-

  1. Open a file
  2. Set variable index and flag to zero.
  3. Run a loop through the file line by line
  4. In this loop we will set the condition for the flag.
  5. After loop, again check the condition for the flag that it is set or not.
  6. If the flag is set i.e. string is found then print the string and line number. If not found then print "String is not found".
  7. After all the step close the file.

Code:-


Output:-


So, there it we find the string with the line. If I have to read that line only then I don't have to read the whole file for reading that particular line having the string we are searching. I just refer to that line and read it.

To learn more python tips and tricks you don't need to google it. Just type codinindia.blogspot.com in your browser then you reach the destination which have lots of python tips and tricks.

I hope you find this post useful. Please Like and share this post and if you have any query please comment it down.

     



Comments