1

I am searching far a particular string using this code:

stringToMatch = 'blah'
matchedLine = ''
#get line
with open(r'path of the text file', 'r') as file:
    for line in file:
        if stringToMatch in line:
            matchedLine = line
            break
#and write it to the file
with open(r'path of the text file ', 'w') as file:
    file.write(matchedLine)

This prints only the string once even if it occurs multiple times. I also want to print all the lines after a particular word occurs. How do i do that?

1
  • Your break says leave the for loop once it found one case. You may need to remove/modify that. Commented May 11, 2020 at 7:25

3 Answers 3

2

Set a flag to keep track of when you've seen the line, and write the lines into the output file in the same loop.

string_to_match = "blah"
should_print = False
with open("path of the text file", "r") as in_file, open("path of another text file", "w") as out_file:
    for line in in_file:
        if string_to_match in line:
            # Found a match, start printing from here on out
            should_print = True
        if should_print:
            out_file.write(line)
Sign up to request clarification or add additional context in comments.

Comments

1
stringToMatch = 'blah'
matchedLine = ''

# get line
lines = ''
match = False
with open(r'path of the text file', 'r') as file:
    for line in file:
        if match:
            # store lines if matches before
            lines += line + '\n'
        elif stringToMatch in line:
            # If matches, just set a flag
            match = True

# and write it to the file
with open(r'path of the text file ', 'w') as file:
    file.write(lines)

Comments

0

You can modify your code like this:-

stringToMatch = 'blah'
matchedLine = ''
#get line
with open(r'path of the text file', 'r') as file:
    for line in file:
        if stringToMatch in line:
            matchedLine += line + '\n'

#and write it to the file
with open(r'path of the text file ', 'w') as file:
    file.write(matchedLine)

Hope you got it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.