Open In App

Python Program to Print Lines Containing Given String in File

Last Updated : 31 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
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



Previous Article
Next Article

Similar Reads

Python - Convert simple lines to bulleted lines using the Pyperclip module
Pyperclip is the cross-platform Python module which is used for copying and pasting the text to the clipboard. Let's suppose you want to automate the task of copying the text and then convert them to the bulleted points. This can be done using the pyperclip module. Consider the below examples for better understanding. Examples: Clipboard Content :
2 min read
Python Program to Count Vowels, Lines, Characters in Text File
In this article, we are going to create a python program that counts vowels, lines, and a number of characters present in a particular text file. ApproachWe have to open the file using open() function in python.Then make three variables, vowel, line and character to count the number of vowels, lines, and characters respectively.Make a list of vowel
2 min read
Python - Reading last N lines of a file
Prerequisite: Read a file line-by-line in PythonGiven a text file fname, a number N, the task is to read the last N lines of the file.As we know, Python provides multiple in-built features and modules for handling files. Let's discuss different ways to read last N lines of a file using Python. File: Method 1: Naive approach In this approach, the id
5 min read
Count number of lines in a text file in Python
Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or a loop approach in Python. Input: line 1 line 2 line 3 Output: 3 Explanation: The Input has 3 number of line in
3 min read
Python - Get number of characters, words, spaces and lines in a file
Given a text file fname, the task is to count the total number of characters, words, spaces, and lines in the file. Python - Get number of characters, words, spaces and lines in a fileAs we know, Python provides multiple in-built features and modules for handling files. Let's discuss different ways to calculate the total number of characters, words
5 min read
Eliminating repeated lines from a file using Python
Let us see how to delete several repeated lines from a file using Python's File Handling power. If the file is small with a few lines, then the task of deleting/eliminating repeated lines from it could be done manually, but when it comes to large files, this is where Python comes to your rescue. Eliminating repeated lines from a file in PythonBelow
6 min read
How to count the number of lines in a CSV file in Python?
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the n
2 min read
Replace Multiple Lines From A File Using Python
In Python, replacing multiple lines in a file consists of updating specific contents within a text file. This can be done using various modules and their associated functions. In this article, we will explore three different approaches along with the practical implementation of each approach in terms of example code and output. Replace Multiple Lin
3 min read
How to read specific lines from a File in Python?
Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers begin with the 0th index. There are various ways
3 min read
Append Text or Lines to a File in Python
Appending text or lines to a file is a common operation in programming, especially when you want to add new information to an existing file without overwriting its content. In Python, this task is made simple with built-in functions that allow you to open a file and append data to it. In this tutorial, we'll explore what it means to append text or
3 min read
Practice Tags :
three90RightbarBannerImg