我有一個非常大的文本文件,我想過濾掉一些行。第一行是標識符和它之後是多行(在不同的行數)這樣的例子:在Python中刪除文本文件的一部分
例如:
fixedStep ch=GL000219.1 start=52818 step=1
1.000000
1.000000
1.000000
1.000000
1.000000
1.000000
1.000000
fixedStep ch=GL000320.1 start=52959 step=1
1.000000
1.000000
1.000000
fixedStep ch=M start=52959 step=1
1.000000
1.000000
這條線是標識符:fixedStep ch=GL000219.1 start=52818 step=1
欲過濾掉所有標識符線包含ch=GL000219.1
和ch=GL000320.1
以及下面的行(數字),並在其下面保留其他標識符和相應的行(數字)。每個標識符重複多次。 這樣的輸出:
fixedStep ch=M start=52959 step=1
1.000000
1.000000
我曾嘗試這樣的代碼:
l = ["ch=GL000219.1", "ch=GL000320.1"] # since I have more identifiers that should be removed
with open('file.txt', 'r') as f:
with open('outfile.txt', 'w') as outfile:
good_data = True
for line in f:
if line.startswith('fixedStep'):
for i in l:
good_data = i not in line
if good_data:
outfile.write(line)
我的代碼不會返回我想要的。你知道如何修改代碼嗎?
添加'break'下'good_data =我不line'如果它變成'FALSE'。 'good_data'對於單行可以取多個值,因爲它自己覆蓋了,所以它只需要爲'i'的最後一個值爲'True'。 – roganjosh
另外,'good_data'需要爲每一行重新設置,否? – roganjosh
我試過但沒有區別。 – john