Finding string in a text file using read()

we are going to search string line by line if the string is found then we will print that string and line number using the read() function.

Python3




with open(r'myfile.txt', 'r') as file:
        # read all content from a file using read()
        content = file.read()
        # check if string present or not
        if 'Line 8' in content:
            print('string exist')
        else:
            print('string does not exist')


Output:

string does not exist

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

In this article, we are going to see how to search for a string in text files using Python

Example:

string = “GEEK FOR GEEKS”
Input: “FOR” 
Output: Yes, FOR is present in the given string.

Text File for demonstration:

myfile.txt

Similar Reads

Finding the index of the string in the text file using readline()

In this method, we are using the readline() function, and checking with the find() function, this method returns -1 if the value is not found and if found it returns 0....

Finding string in a text file using read()

...

Search for a String in Text Files using enumerate()

we are going to search string line by line if the string is found then we will print that string and line number using the read() function....

Contact Us