Open In App
Related Articles

Python Program to Print Lines Containing Given String in File

Like Article
Save Article
Report issue

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:


  • 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:


# 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
    # 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
    # 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+ "\"!")
        # displaying the lines 
        # containing given string
        lineLen = len(new_list)
        print("\n**** Lines containing \"" +text+ "\" ****\n")
        for i in range(lineLen):
# entering except block
# if input file doesn't exist 
except :
  print("\nThe file doesn't exist!")



Lines containing string

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