如何在Python中使用特定关键字删除后续行

时间:2013-01-14 08:38:01

标签: python text file-io

在找到关键字“banana”的特定行后,我想删除后续行,在本例中为“berry”。

Sample.txt的

orange
apple
banana
berry
melon

然而,我的剧本删除了“香蕉”而不是“浆果”....为什么?

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,

3 个答案:

答案 0 :(得分:3)

这样做:

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)

这利用迭代fin对象,因此它不会看到下一行 - 这意味着你不必担心设置/取消设置标志......(这可能导致错误)

答案 1 :(得分:2)

这样的事情:

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

答案 2 :(得分:1)

请试试这个

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,