Skip to content Skip to sidebar Skip to footer

How To Delete One Line After The Specific Word With Python

I have a text file (input.txt) and it contains: COMPDAT First line 123 456 Second line 4d5 fdf COMPDAT Computer 459 Computer 999 COMPDAT Mouse qwerty main 478 Now I need t

Solution 1:

import fileinput    
fin = fileinput.input('input.txt', inplace=True)

for line in fin:    
    print(line,end='')
    if line.strip() == 'COMPDAT':    
        next(fin, None)

Solution 2:

first read the file, get all lines that you want, and then write those lines in same file.

input_file = open("input.txt", 'r')
prev_line = False
lines =[]
for line in input_file:
 ifnot prev_line:
    lines.append(line)
 prev_line=False
 if"COMPDAT"in line:
    prev_line=True
input_file.close()

input_file = open("input.txt", 'w')
for line inlines:
   input_file.write(line)
input_file.close()

Solution 3:

Another possibility using a generator, based on @Sanjay's answer.

def line_and_line_before(file):
    prev_line = None
    for line in file:
        yield (prev_line, line)
        prev_line = line

input_file = open("input.txt", 'r')
lines = []

for prev_line, line in line_and_line_before(input_file):
     ifnot prev_line or"COMPDAT"notin prev_line:
         lines.append(line)

input_file.close()

input_file = open("input.txt", 'w')
for line inlines:
    input_file.write(line)
input_file.close()

Post a Comment for "How To Delete One Line After The Specific Word With Python"