Don't write final new line character to a file
Question: I have looked around StackOverflow and couldn't find an answer to my specific
question so forgive me if I have missed something.

    
    
    import re
    
    target = open('output.txt', 'w')
    
    for line in open('input.txt', 'r'):
        match = re.search(r'Stuff', line)
        if match:
            match_text = match.group()
            target.write(match_text + '\n')
        else:
            continue
    target.close()
    

The file I am parsing is huge so need to process it line by line.

This (of course) leaves an additional newline at the end of the file.

How should I best change this code so that on the final iteration of the 'if
match' loop it doesn't put the extra newline character at the end of the file.
Should it look through the file again at the end and remove the last line
(seems a bit inefficient though)?

The existing StackOverflow questions I have found cover removing all new lines
from a file.

If there is a more pythonic / efficient way to write this code I would welcome
suggestions for my own learning also.

Thanks for the help!


Answer: Write the newline of each line at the beginning of the _next_ line. To avoid
writing a newline at the beginning of the first line, use a variable that is
initialized to an empty string and then set to a newline in the loop.

    
    
    import re
    
    with open('input.txt') as source, open('output.txt', 'w') as target:
    
        newline = ''
        for line in source:
            match = re.search(r'Stuff', line)
            if match:
                target.write(newline + match.group())
                newline = '\n'
    

I also restructured your code a bit (the `else: continue` is not needed,
because what else is the loop going to do?) and changed it to use the `with`
statement so the files are automatically closed.

