Python Forum
Delete line before and after needle
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Delete line before and after needle
#1
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)
Reply
#2
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.
Recommended Tutorials:
Reply
#3
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:
    ...
    ...
Reply
#4
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Find and delete above a certain line in text file cubangt 12 3,453 Mar-18-2022, 07:49 PM
Last Post: snippsat
  [Solved] Delete a line in a dataframe using .reset_index() and .drop() ju21878436312 2 2,677 Feb-25-2022, 02:55 PM
Last Post: ju21878436312
  Delete all contents of a file from the fifth line? PythonNPC 1 1,900 Apr-18-2020, 09:16 AM
Last Post: buran
  Compare element of list with line of file : if match, delete line silfer 4 3,511 Jul-21-2018, 02:44 PM
Last Post: silfer
  delete line from a text file thesisonews 2 27,531 Mar-20-2018, 08:30 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020