ItSolutionStuff.com

Python Search String in File and Print Line Example

By Hardik Savani • October 30, 2023
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: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Check If String Contains Word in Python?

Read Now →

How to Set and Get Environment Variables in Python?

Read Now →

How to Generate Random Float Numbers in Python?

Read Now →

Python Generate Random Number Between 0 to 1 Example

Read Now →

Python Generate Random Number Between 1 and 10 Example

Read Now →

Python Read Text File into List Example

Read Now →

How to Read Text File Line by Line in Python?

Read Now →

How to Read a Text File in Python?

Read Now →

How to Append Text or Lines to a Text File in Python?

Read Now →

Python Generate Text File from List Example

Read Now →

Python Create Text File If Not Exists Example

Read Now →

Python Create Text File in Specific Directory Example

Read Now →

How to Create Multiline Text File in Python?

Read Now →

Python Create an Empty Text File Example

Read Now →