How to Print Lines Containing Given String in File using Python?

In this article, we will show you how to print all the lines that contain a given specific string in a text file using Python. This is a common task when searching through files for specific content or filtering data.

Let's assume we have a text file named ExampleTextFile.txt with the following content ?

Sample File Content

Good morning to TutorialsPoint
This is TutorialsPoint sample File
Consisting of Specific
source codes in Python,Seaborn,Scala
Summary and Explanation
Welcome to TutorialsPoint
Learn with a joy
Good morning to TutorialsPoint

Algorithm (Steps)

Following are the steps to print lines containing a given string ?

  • Open the text file in read mode using open() function

  • Define the string you want to search for

  • Iterate through each line in the file

  • Check if the search string exists in the current line using the in operator

  • Print the line if the string is found

The in keyword is used to check whether a value exists in a sequence (string, list, tuple, etc.) and returns True if found, False otherwise.

Method 1: Using Basic File Reading

This approach reads the file line by line and checks for the target string ?

# Create sample file content for demonstration
with open("ExampleTextFile.txt", "w") as f:
    f.write("""Good morning to TutorialsPoint
This is TutorialsPoint sample File
Consisting of Specific
source codes in Python,Seaborn,Scala
Summary and Explanation
Welcome to TutorialsPoint
Learn with a joy
Good morning to TutorialsPoint""")

# Search for lines containing specific string
search_string = "to TutorialsPoint"
print(f'Lines containing "{search_string}":')

with open("ExampleTextFile.txt", 'r') as file:
    for line_number, line in enumerate(file, 1):
        if search_string in line:
            print(f"Line {line_number}: {line.strip()}")
Lines containing "to TutorialsPoint":
Line 1: Good morning to TutorialsPoint
Line 6: Welcome to TutorialsPoint
Line 8: Good morning to TutorialsPoint

Method 2: Case-Insensitive Search

For case-insensitive searching, convert both the line and search string to lowercase ?

search_string = "tutorialspoint"
print(f'Lines containing "{search_string}" (case-insensitive):')

with open("ExampleTextFile.txt", 'r') as file:
    for line_number, line in enumerate(file, 1):
        if search_string.lower() in line.lower():
            print(f"Line {line_number}: {line.strip()}")
Lines containing "tutorialspoint" (case-insensitive):
Line 1: Good morning to TutorialsPoint
Line 2: This is TutorialsPoint sample File
Line 6: Welcome to TutorialsPoint
Line 8: Good morning to TutorialsPoint

Method 3: Using List Comprehension

A more concise approach using list comprehension to collect matching lines ?

search_string = "Python"

with open("ExampleTextFile.txt", 'r') as file:
    matching_lines = [line.strip() for line in file if search_string in line]

print(f'Lines containing "{search_string}":')
for i, line in enumerate(matching_lines, 1):
    print(f"{i}. {line}")
Lines containing "Python":
1. source codes in Python,Seaborn,Scala

Method 4: Using Regular Expressions

For more complex pattern matching, use the re module ?

import re

pattern = r"TutorialsPoint"
print(f'Lines matching pattern "{pattern}":')

with open("ExampleTextFile.txt", 'r') as file:
    for line_number, line in enumerate(file, 1):
        if re.search(pattern, line):
            print(f"Line {line_number}: {line.strip()}")
Lines matching pattern "TutorialsPoint":
Line 1: Good morning to TutorialsPoint
Line 2: This is TutorialsPoint sample File
Line 6: Welcome to TutorialsPoint
Line 8: Good morning to TutorialsPoint

Comparison

Method Best For Case Sensitive
Basic in operator Simple string matching Yes
Lowercase comparison Case-insensitive search No
List comprehension Collecting all matches Yes
Regular expressions Complex pattern matching Configurable

Conclusion

Use the basic in operator for simple string searches in files. For case-insensitive searches, convert strings to lowercase. Use regular expressions for complex pattern matching requirements.

Updated on: 2026-03-26T21:27:29+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements