从文本文件中删除特定行

时间:2013-07-27 08:55:47

标签: python python-2.7

我有一个文本文件:

>E8|E2|E9D
Football is a good game
Its good for health
you can play it every day
>E8|E2|E10D
Sequence unavailable
>E8|E2|EKB
Cricket
>E87|E77|E10D
Sequence unavailable
>E27|E97|E10D
Sequence unavailable
>E8|E2|E9D
Sequence unavailable

我编写了以下代码来检测此文件中的Sequence unavailable并将其删除:

with open('input.txt') as f1, open('output.txt', 'w') as f2,\
                                                  open('temp_file','w') as f3:
    lines = []       # store lines between two `>` in this list
    for line in f1:
        if line.startswith('>'):
            if lines:
                f3.writelines(lines)
                lines = [line]
            else:
                lines.append(line)
        elif line.rstrip('\n') == 'Sequence unavailable':
            f2.writelines(lines + [line])
            lines = []
        else:
            lines.append(line)

    f3.writelines(lines)

os.remove('input.txt')
os.rename('temp_file', 'input.txt')

但我真正想要的是删除给定问题的所有可用序列(>行的最后一列)。

例如,即使E9D后面有行,如果E9D的另一个条目带有Sequence unavailable,则不应将任何条目写入输出文件:

input.txt中

>E8|E2|E9D
Football is a good game
Its good for health
you can play it every day
>E8|E2|E10D
Sequence unavailable
>E8|E2|EKB
Cricket
>E87|E77|E10D
Sequence unavailable
>E27|E97|E10D
Sequence unavailable
>E8|E2|E9D
Sequence unavailable

output.txt的

>E8|E2|EKB
Cricket

此处只有EKB个问题有条目。

2 个答案:

答案 0 :(得分:1)

def get_name(line):
    return line[1:].rsplit('|', 1)[-1].strip()

with open('input.txt') as f, open('output.txt', 'w') as fout:
    name = ''

    # Phase 1: Find unavailable sequence
    unavailable = set()
    for line in f:
        if line.startswith('>'):
            name = get_name(line)
        else:
            if 'Sequence unavailable' in line:
                unavailable.add(name)

    # Phase 2: Filter avilable sequence
    f.seek(0)
    keep = False
    for line in f:
        if line.startswith('>'):
            name = get_name(line)
            keep = name not in unavailable
        if keep:
            fout.write(line)

答案 1 :(得分:0)

您可以采用其他更简单的方法。您可以将其替换为“”

,而不是删除该行
import fileinput
import sys

f=open('input.txt')
line = f.readline()
f.close()
words = line.split()
for word in words:
    line = line.replace("Sequence unavailable","")
    line = line.replace("\n","")

我没有执行此代码,但我认为逻辑是正确的。请注意,您必须使用第二次更换,因为每次都会有新行。