简体   繁体   English

如何在Python中删除具有特定关键字的行后的后续行

[英]How to Delete Subsequent Line After A Line With Specific Keyword in Python

After finding a specific line with keyword "banana", I would like to delete the subsequent line, in this case, "berry". 找到带有关键字“ banana”的特定行后,我想删除下一行,在这种情况下为“ berry”。

Sample.txt Sample.txt

orange
apple
banana
berry
melon

My script, however, deletes "banana" not "berry"....Why? 但是,我的脚本删除了“香蕉”而不是“浆果”。...为什么?

import fileinput

filename = r"C:\sample.txt"
for linenum,line in enumerate(fileinput.FileInput(filename, inplace=1)):
    if "banana" in line:
        counter = linenum + 1
        if linenum == counter:
            line.strip()
    else:
        print line,

Do it like this: 像这样做:

import fileinput

fin = fileinput.input('/home/jon/text.txt', inplace=1)
for line in fin:
    print line,
    if line.strip() == 'banana':
        next(fin, None) # as suggested by @thg435 doesn't hurt to use default to avoid StopIteration (as next iteration will just be a no-op anyway)

This takes advantage of iterating the fin object so it doesn't see the next row - meaning you don't have to worry about setting/unsetting flags... (which can lead to errors) 这利用了fin对象的迭代,因此它不会看到下一行-这意味着您不必担心设置/取消设置标志...(这可能会导致错误)

Something like this: 像这样:

flag = False
with open("C:\sample.txt") as in_f:
    for line in in_f:
        if flag: # previous line have "banana", so skip this line
            flag = False
            continue
        if "banana" in line: # set flag to skip line
            flag = True
        print line

Please try this 请尝试这个

filename = r"sample.txt"
counter = -1
for linenum,line in enumerate(fileinput.FileInput(filename, inplace=1)):
    if "banana" in line:
        counter = linenum + 1
    if linenum == counter:
        line.strip()
    else:
        print line,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何逐行提取直到特定的关键字,然后声明为变量 - How to extract line after line till a specific keyword and then declare to a variable 如何使用Python删除特定单词后的一行 - How to delete one line after the specific word with Python 如何从 python 上的文件中的特定行删除直到特定行 - How to delete from specific line until specific line in a file on python 如何从“关键字” python开始替换特定行中的特定单词 - How to replace a specific word in specific line starting with a “keyword” python 如何在 Python 中使用循环删除特定行上的 CRLF - How to delete CRLFs on a specific line with a loop in Python 当在 Python 中使用正则表达式之间有单词时,如何提取特定关键字之后的下一行? - How to extract the next line after a specific keyword when there are words in between using regex in Python? 如何删除特定行并在python中将其替换 - How to delete a specific line and replace it in python 如何使用python删除特定单词之前的一行 - How to delete a line before specific word with python 如果行在python中有特定的单词,如何删除整行 - how to delete the entire line if line has specific word in python 如何仅删除包含特定关键字的一行? 并将该行保存到另一个文件中 - How to delete only one line containing a specific keyword? And save that line into another file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM