Python Program to Print all the Pattern that Matches Given Pattern From a File

Finding lines in a file that match a particular pattern is a common operation with many applications, such as log analysis, text processing, and data filtering. In this article, we will discuss how to create a Python program that prints all patterns matching a given pattern from a file.

Syntax

with open("file_name.txt", "r") as file:
    content = file.read()

The open() function works with the 'with' statement to open the file safely. The open function accepts two parameters: the filename and the mode ('r' for reading).

Algorithm

The following steps outline our approach:

  • Create a text file with a star pattern and save it

  • Generate the same pattern programmatically using a loop

  • Read the file content and compare it with our generated pattern

  • Check if the patterns match exactly

Method 1: Basic Pattern Matching

First, let's create a simple star pattern and check if it matches the content in a file:

# Create the pattern programmatically
pattern_lines = []
for i in range(1, 5):
    pattern_lines.append("*" * i)

generated_pattern = "\n".join(pattern_lines)
print("Generated pattern:")
print(generated_pattern)
Generated pattern:
*
**
***
****

Method 2: File Content Comparison

Now let's create a file with the pattern and check for matches:

# First, create a sample file with pattern content
with open("pattern.txt", "w") as file:
    for i in range(1, 5):
        file.write("*" * i + "\n")

# Generate the pattern to match
pattern_lines = []
for i in range(1, 5):
    pattern_lines.append("*" * i)

generated_pattern = "\n".join(pattern_lines)

# Read the file and check for pattern match
with open("pattern.txt", "r") as file:
    file_content = file.read().strip()

if generated_pattern == file_content:
    print("Exact pattern match found!")
    print("Pattern from file:")
    print(file_content)
else:
    print("No exact match found")
Exact pattern match found!
Pattern from file:
*
**
***
****

Method 3: Using Regular Expressions

For more complex pattern matching, we can use regular expressions:

import re

# Create a sample file with mixed content
with open("mixed_content.txt", "w") as file:
    file.write("Some text here\n")
    file.write("*\n")
    file.write("**\n") 
    file.write("***\n")
    file.write("****\n")
    file.write("More text here\n")

# Read file and find all star patterns
with open("mixed_content.txt", "r") as file:
    content = file.read()

# Find all lines that contain only stars
star_pattern = re.compile(r'^\*+$', re.MULTILINE)
matches = star_pattern.findall(content)

print("Found star patterns:")
for match in matches:
    print(match)
Found star patterns:
*
**
***
****

Comparison

Method Use Case Complexity
Basic String Comparison Exact pattern matching Simple
Line-by-line Check Partial pattern matching Moderate
Regular Expressions Complex pattern matching Advanced

Advantages

  • Efficient data extraction ? Extract specific information from large files quickly

  • Data analysis ? Useful for log analysis and text mining applications

  • Built-in support ? Python's re module provides powerful pattern matching capabilities

  • Flexibility ? Can handle simple string matching to complex regular expressions

Conclusion

Pattern matching from files is essential for text processing and data analysis. Use simple string comparison for exact matches, and regular expressions for complex pattern detection. The choice depends on your specific requirements and pattern complexity.

Updated on: 2026-03-27T07:07:51+05:30

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements