KingQeen
KingQeen

Reputation: 29

how to print from a particular line from text file in python

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?

Upvotes: 1

Views: 316

Answers (3)

Ankit Badadiya
Ankit Badadiya

Reputation: 26

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.

Upvotes: 0

ErdoganOnal
ErdoganOnal

Reputation: 880

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)

Upvotes: 1

AKX
AKX

Reputation: 168843

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)

Upvotes: 2

Related Questions