How to Find String in File and Print Line in Python?

30-May-2023

.

Admin

How to Find String in File and Print Line in Python?

Hi Dev,

This simple article demonstrates of how to find strings in a file and print lines in Python. I would like to share with you Python find string in a text file and print line. let’s discuss Python's search text file for string and print line. you will learn Python to get lines containing strings from files. Let's get started with Python and get a line with a string in a file.

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 :


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

#Python