Searching for a String in a File and Printing the Matching Line in Python

AuthorSumit Dey Sarkar

Pubish Date30 Apr 2023

categoryPython

In this tutorial we will see Searching for a String in a File and Printing the Matching Line in Python.

 

Searching for a String in a File and Printing the Matching Line in Python

 

Searching for a string in a file and printing the matching line in Python

 

Python allows you to use this code to look for a string in a file and print the line where the string appears:

# The string you want to search for
search_string = "example" 
# The path to the file you want to search in
file_path = "file.txt"  

with open(file_path, "r") as file:
    for line in file:
        if search_string in line:
            print(line.strip())

In the above code, we first define the search_string variable as the string we want to search for, and the file_path variable as the path to the file we want to search in.

 

Then we use the with open() statement to open the file in read mode and create a file object called file. We use a for loop to traverse through every line in the file, and an if statement to see whether the search_string is present in the current line. Using the print() function and the strip() method to eliminate any unnecessary whitespace at the beginning or end of the line, we print the line if it is.

 

Keep in your mind that this code will only print the first line which contains the search_string. If you want to print all lines that have the string then you can remove the break statement.

 

Comments 0

Leave a comment