Skip to content Skip to sidebar Skip to footer

Remove String And All Lines Before String From File

I have a filename with thousands of lines of data in it. I am reading in the filename and editing it. The following tag is about ~900 lines in or more (it varies per file):

Solution 1:

You can use a flag like tag_found to check when lines should be written to the output. You initially set the flag to False, and then change it to True once you've found the right tag. When the flag is True, you copy the line to the output file.

TAG = '<Report name="test" xmlns:cm="http://www.domain.org/cm">'

tag_found = Falsewithopen('tag_input.txt') as in_file:
    withopen('tag_output.txt', 'w') as out_file:
        for line in in_file:
            ifnot tag_found:
                if line.strip() == TAG:
                    tag_found = Trueelse:
                out_file.write(line)

PS: The with open(filename) as in_file: syntax is using what Python calls a "context manager"- see here for an overview. The short explanation of them is that they automatically take care of closing the file safely for you when the with: block is finished, so you don't have to remember to put in my_file.close() statements.

Post a Comment for "Remove String And All Lines Before String From File"