Python Forum

Full Version: Delete line before and after needle
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Everyone!

I need some help to make a code,
I want to make a code which can find a certain string, then delete the line containing it and the line above and below it.
I could make a code to delete the line with the string but how to delete the line above and below also?

For Example
Good Boy
Bad Boy
Sad Boy
Happy Boy

So the code needs to find string "bad" and then delete that line and the line above and below, leaving Only-
Happy Boy

My code only deletes the line containing the string, i wanna code to delete the line above and below as well.
Thanks in advance

bad_words = ['bad']

with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)
Quote:I could make a code to delete the line with the string but how to delete the line above and below also?
You are going to have to find what line number/index the needle is on, so you can delete before and after the needle's line as well.
Convert your file into a list of lines:

with open('oldfile.txt') as oldfile:
    list_of_lines = oldfile.readlines()

with open('newfile.txt', 'w') as newfile:
    ...
    ...
Or, just don't write a line unless the previous line is fine.
text_to_avoid = "bad"

with open("original.txt") as infile:
    with open("out.txt", "w") as outfile:
        last_line = ""
        line_before_last = ""
        for ndx, line in enumerate(infile):
            if ndx >= 2:
                if text_to_avoid not in line.lower() \
                        and text_to_avoid not in last_line.lower() \
                        and text_to_avoid not in line_before_last.lower():
                    print(last_line, file=outfile)
            line_before_last = last_line
            last_line = line
        if text_to_avoid not in last_line.lower() \
                and text_to_avoid not in line_before_last.lower():
            print(last_line, file=outfile)