How to Print Lines Containing a String in a File Using Python?

Estimated read time 2 min read

You can print lines containing a string in a file using Python by following these steps:

  1. Open the file using the open() function and assign it to a file object.
  2. Read the contents of the file using the readlines() method to get a list of strings, where each string represents a line in the file.
  3. Use a for loop to iterate over each line in the list of strings.
  4. Use the if statement to check if the string you’re searching for is in the current line.
  5. If the string is in the line, print the line using the print() function.

Here’s an example code snippet that shows how to do this:

# Open the file
with open('filename.txt', 'r') as file:
    # Read the contents of the file and store them in a list of strings
    lines = file.readlines()

# Define the string you're searching for
search_string = 'example'

# Iterate over each line in the list of strings
for line in lines:
    # Check if the string is in the current line
    if search_string in line:
        # If the string is in the line, print the line
        print(line)
]

In this example, the code opens the file filename.txt, reads its contents using readlines(), and stores each line in a list of strings called lines. It then defines the string search_string that it wants to find in the file. Finally, it iterates over each line in the lines list, checks if search_string is in the line, and prints the line if it is found.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply