Python Program to Print Lines Containing Given String in File
In this article, we are going to see how to fetch and display lines containing a given string from a given text file. Assume that you have a text file named geeks.txt saved on the location where you are going to create your python file.
Here is the content of the geeks.txt file:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
- Load the text file into the python program to find the given string in the file.
- Ask the user to enter the string that you want to search in the file.
- Read the text file line by line using readlines() function and search for the string.
- After finding the string, print that entire line and continue the search.
- If the string is not found in the entire file, display the proper verdict.
Below is the implementation: