[英]How to delete one line after the specific word with Python
I have a text file ( input.txt
) and it contains: 我有一个文本文件(
input.txt
),它包含:
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. 现在,我需要删除
input.txt
文件中每个COMPDAT
关键字之后的第一行。
How can I do that with Python? 如何使用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)
import fileinput
fin = fileinput.input('input.txt', inplace=True)
for line in fin:
print(line,end='')
if line.strip() == 'COMPDAT':
next(fin, None)
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()
Another possibility using a generator, based on @Sanjay's answer. 基于@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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.