How can I read a file to a string starting at a given word without knowing the line number?

12,835

Solution 1

useful = []
with open ("Report.txt", "r") as myfile:
    for line in myfile:
        if "===" in line:
            break
    for line in myfile:
        useful.append(line)
a_string = "".join(useful)

I would however prefer to hide it away in a generator, like this:

def report_iterator():
    with open ("Report.txt", "r") as myfile:
        for line in myfile:
            if "===" in line:
                break
        for line in myfile:
            yield line

for line in report_iterator():
    # do stuff with line

All the filtering and nitpicking is done in the generator function, and you can separate the logic of "filtering input" from the logic of "working with the input".

Solution 2

You could read line by line, and by default not store the lines. When you get the line starting with '==', then all lines you read until you read the second '==' line you store in your string or list.

Share:
12,835
Brad Conyers
Author by

Brad Conyers

Updated on July 15, 2022

Comments

  • Brad Conyers
    Brad Conyers almost 2 years

    I have test results in a log file that are formatted like:

    useless info

    useless info

    ======================

    useful info

    useful info

    ======================

    test success

    The number of lines in each section can vary, so I want to check for the first appearance of the double equal character '==' and read that line until the end of the file into a string. Currently I'm using the following code to read the whole file into the string.

    with open ("Report.txt", "r") as myfile:
        data = myfile.read()
    

    Thanks for the help!