Python – How to search for a string in text files?
In this article, we are going to see how to search for a particular string in a text file.
Consider below text File :
Example 1: we are going to search string line by line if the string found then we will print that string and line number.
Steps:
- Open a file.
- Set variables index and flag to zero.
- Run a loop through the file line by line.
- In that 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’.
- Close a file.
Code:
- Python3
string1 = 'coding' # opening a text file file1 = open ( "geeks.txt" , "r" ) # setting flag and index to 0 flag = 0 index = 0 # Loop through the file line by line for line in file1: index + = 1 # checking string is present in line or not if string1 in line: flag = 1 break # checking condition for string found or not if flag = = 0 : print ( 'String' , string1 , 'Not Found' ) else : print ( 'String' , string1, 'Found In Line' , index) # closing text file file1.close() |
Output:
Example 2: We are just finding string is present in the file or not.
Step:
- open a file.
- Read a file and store it in a variable.
- check condition using ‘in’ operator for string present in the file or not.
- If the condition true then print the message ‘string is found’ otherwise print ‘string not found’.
- Close a file.
Code:
- Python3
string1 = 'portal' # opening a text file file1 = open ( "geeks.txt" , "r" ) # read file content readfile = file1.read() # checking condition for string found or not if string1 in readfile: print ( 'String' , string1, 'Found In File' ) else : print ( 'String' , string1 , 'Not Found' ) # closing a file file1.close() |
Output:
Last Updated on March 1, 2022 by admin