Python Search String in File and Print Line Example

By Hardik Savani October 30, 2023 Category : Python

Hey,

In this post, we will learn python find string in text file and print line. we will help you to give an example of python search text file for string and print line. I explained simply about python get line containing string from file. you will learn python get line with string in file. Alright, let us dive into the details.

If you are looking to find a string in a text file and print a line using a python program. then there are lots of ways to do this. Here, I will give you a very simple example to search for text in a file python. we will create example.txt with some dummy text. we will find the "Line 3" string from that text file. you can see the following code here:

Example 1:

Here, we will create an "example.txt" file as like below:

example.txt

This is Line 1
This is Line 2
This is Line 3
This is Line 4
This is Line 5

Now, we will create main.py file and find string from that file as like the below code:

main.py

findString = "Line 3"
  
# python find string in text file and print line
with open('example.txt') as f:
    lines = f.readlines()
    for line in lines:
          
        if line.find(findString) != -1:
            print('String Found in Line Number:', lines.index(line) + 1)
            print('Line Content:', line)

Output:

String Found in Line Number: 3
Line Content: This is Line 3

I hope it can help you...

Tags :
Shares