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
- Get Last 2 Digits of Number in Python Tutorial Example
- How to Sum of First and Last Digit of Number in Python?
- How to Get First and Last Digit of Number in Python?
- Get the Last Digit of Number in Python Tutorial Example
- Get the First Digit of Number in Python Tutorial Example
- How to Remove All Decimals from Number in Python?
- How to Convert String to Float with 2 Decimal Places in Python?
- How to Format Number to 2 Decimal Places in Python?