Python Program to Print Lines Containing Given String in File
Last Updated :
31 Aug, 2021
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:
Approach:
- 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:
Python3
file_name = input ( "Enter The File's Name: " )
try :
file_read = open (file_name, "r" )
text = input ( "Enter the String: " )
lines = file_read.readlines()
new_list = []
idx = 0
for line in lines:
if text in line:
new_list.insert(idx, line)
idx + = 1
file_read.close()
if len (new_list) = = 0 :
print ( "\n\"" + text + "\" is not found in \"" + file_name + "\"!" )
else :
lineLen = len (new_list)
print ( "\n**** Lines containing \"" + text + "\" ****\n" )
for i in range (lineLen):
print (end = new_list[i])
print ()
except :
print ( "\nThe file doesn't exist!" )
|
Output:
Lines containing string
Share your thoughts in the comments
Please Login to comment...