Python Search String in File and Print Line Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Check If String Contains Word in Python?
- How to Set and Get Environment Variables in Python?
- How to Generate Random Float Numbers in Python?
- Python Generate Random Number Between 0 to 1 Example
- Python Generate Random Number Between 1 and 10 Example
- Python Read Text File into List Example
- How to Read Text File Line by Line in Python?
- How to Read a Text File in Python?
- How to Append Text or Lines to a Text File in Python?
- Python Generate Text File from List Example
- Python Create Text File If Not Exists Example
- Python Create Text File in Specific Directory Example
- How to Create Multiline Text File in Python?
- Python Create an Empty Text File Example