我有一個文本文件:刪除從文本文件中的特定行
>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
行,如果沒有與Sequence unavailable
爲E9D
另一個條目沒有條目應該被寫入到輸出文件:
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
輸出。 txt
>E8|E2|EKB
Cricket
這裏只有EKB
問題有條目。
感謝@Martijn彼得斯,讓它很容易理解 – Rocket