简体   繁体   中英

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".

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)

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM