qasim
qasim

Reputation: 437

delete an empty line before matched pattern

I am trying to write a new line before matching 'find me' but my code writes an empty line to the output file. How can I get rid of that empty line (line after 41.4 gram)?

    with open("input.txt", "r") as infile:
        readcontent = infile.readlines()

    with open("output.txt", "w") as out_file:
        for line in readcontent:
            if line.strip() == 'find me':
                out_file.write('Added New line')
            out_file.write(line)

input.txt:

[atom]
molecules 
41.4 gram

find me
2.1 kcal
completed

obtained output.txt:

[atom]
molecules 
41.4 gram

Added New line
find me
2.1 kcal
completed

Desired output.txt:

[atom]
molecules 
41.4 gram
Added New line
find me
2.1 kcal
completed

Upvotes: 0

Views: 58

Answers (2)

Reroute
Reroute

Reputation: 273

As you are just chasing a blank line. we throw in .isspace as a check and you never write any lines that are blank or only contain whitespace characters.

with open("input.txt", "r") as infile:
    readcontent = infile.readlines()

with open("output.txt", "w") as out_file:
    for line in readcontent:
        if line.strip() == 'find me':
            out_file.write('Added New line')
        if not line.isspace:
            out_file.write(line)

Edit: Changed based on commenter below

Upvotes: 1

blhsing
blhsing

Reputation: 106936

In other words, you want to skip outputting a blank line if the next line is find me. Since you already have all the lines in readcontent, you can simply peek ahead with the next index:

with open("input.txt", "r") as infile:
    readcontent = infile.readlines()

with open("output.txt", "w") as out_file:
    for index, line in enumerate(readcontent):
        if not line.strip() and readcontent[index + 1].strip() == 'find me':
            continue
        if line.strip() == 'find me':
            out_file.write('Added New line\n')
        out_file.write(line)

Upvotes: 1

Related Questions