如何使用Python删除特定单词后面的一行

时间:2017-04-24 12:05:28

标签: python

我有一个文本文件(input.txt),它包含:

COMPDAT

First line 123 456

Second line 4d5 fdf

COMPDAT

Computer 459

Computer 999

COMPDAT

Mouse qwerty

main 478

现在,我需要删除COMPDAT文件中每个input.txt关键字后面的第一行 我怎么能用Python做到这一点?

我尝试使用此脚本,但是,它在每个现有行之间添加一个空行:

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

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

首先读取文件,获取所需的所有行,然后将这些行写在同一个文件中。

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()

答案 2 :(得分:0)

使用发电机的另一种可能性,基于@ Sanjay的回答。

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()