Al_Pacino
Al_Pacino

Reputation: 45

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 to delete the first lines after each COMPDAT keyword in my input.txt file.
How can I do that with Python?

I tried to use this script, however, it adds an empty line between each existing lines:

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

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

Upvotes: 0

Views: 691

Answers (3)

B. Barbieri
B. Barbieri

Reputation: 1139

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):
     if not prev_line or "COMPDAT" not in prev_line:
         lines.append(line)

input_file.close()

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

Upvotes: 0

Sanjay
Sanjay

Reputation: 2008

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:
 if not 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 in lines:
   input_file.write(line)
input_file.close()

Upvotes: 0

Smart Manoj
Smart Manoj

Reputation: 5844

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

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

Upvotes: 1

Related Questions