我有一个文本文件(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)
答案 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()