• Register
110 points
7

 Find a string in a file in python 

Today we will see in our website kodlogs how to find the strings in a file in Python programming language. For this you have to use loop whether there are strings in the file or not.  Perform a set of different instructions in case the condition is correct or incorrect. The most important thing in a computer's ability is that it can repeat a set of instructions over and over again until a program meets a certain condition.  It keeps repeating. To do this process of repeating, you have to use loop statement. Today we will learn the same in our website kodlogs. With the help of loop, string can be found from the file. 

Today Tania, it will show you whether there are strings in the text file. If so, print (x)If not, then print( y). This code always proves to be true for some reason. We can use for loop to check the list.  Is there a string line in each iteration or not? The whole game is played inside a loop. The process of reading string data from a file is almost the same as writing.  Today in kodlogs we are going to see how to find a particular string in a text file.

Syntax 

  • Open a file.
  • Set variables index and flag to zero.
  • Run a loop through the file line by line.
  • Loop check condition using the ‘in’ operator for string present in line or not. If found flag to 0.
  • After Loop again check condition for the flag is set or not. If set string found then print a string and line number otherwise simply print the message ‘String not found’.
  • File close
Example 
string1 = 'Kodlogs '


file1 = open("Tania".txt", "r") 

flag = 0

index = 0

for line in file1:   

    index + = 1 


    if string1 in line: 

        

      flag = 1

      break

if flag == 0:  

   print('String', string1 , 'Not Found')  

else:  

   print('String', string1, 'Found In Line', index) 
     
file1.close()  

                   ( OUTPUT )

String  Kodlogs found in line 5

 

 

110 points
7