Open In App
Related Articles

Python Program to Print Lines Containing Given String in File

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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

# Python Program to Print Lines
# Containing Given String in File
  
# input file name with extension
file_name = input("Enter The File's Name: ")
  
# using try catch except to
# handle file not found error.
  
# entering try block
try:
  
    # opening and reading the file 
    file_read = open(file_name, "r")
  
    # asking the user to enter the string to be 
    # searched
    text = input("Enter the String: ")
  
    # reading file content line by line.
    lines = file_read.readlines()
  
    new_list = []
    idx = 0
  
    # looping through each line in the file
    for line in lines:
          
        # if line have the input string, get the index 
        # of that line and put the
        # line into newly created list 
        if text in line:
            new_list.insert(idx, line)
            idx += 1
  
    # closing file after reading
    file_read.close()
  
    # if length of new list is 0 that means 
    # the input string doesn't
    # found in the text file
    if len(new_list)==0:
        print("\n\"" +text+ "\" is not found in \"" +file_name+ "\"!")
    else:
  
        # displaying the lines 
        # containing given string
        lineLen = len(new_list)
        print("\n**** Lines containing \"" +text+ "\" ****\n")
        for i in range(lineLen):
            print(end=new_list[i])
        print()
  
# entering except block
# if input file doesn't exist 
except :
  print("\nThe file doesn't exist!")

                    

Output:

Lines containing string



Last Updated : 31 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads