0

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

样本.txt

orange
apple
banana
berry
melon

然而,我的脚本删除的是“banana”而不是“berry”……为什么?

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,
4

3 回答 3

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对象的优势,因此它看不到下一行 - 这意味着您不必担心设置/取消设置标志......(这可能导致错误)

于 2013-01-14T08:54:34.157 回答
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
于 2013-01-14T08:47:25.357 回答
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,
于 2013-01-14T08:54:34.750 回答