2017-07-26 266 views
0

我有一個非常大的文本文件,我想過濾掉一些行。第一行是標識符和它之後是多行(在不同的行數)這樣的例子:在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.1ch=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) 

我的代碼不會返回我想要的。你知道如何修改代碼嗎?

+0

添加'break'下'good_data =我不line'如果它變成'FALSE'。 'good_data'對於單行可以取多個值,因爲它自己覆蓋了,所以它只需要爲'i'的最後一個值爲'True'。 – roganjosh

+0

另外,'good_data'需要爲每一行重新設置,否? – roganjosh

+0

我試過但沒有區別。 – john

回答

0

在從文本文件中讀取字符串後,需要將字符串(文本文件的內容)拆分爲行。使用

打印(F)

讀取到f後,你會發現這是一個字符串,沒有行。

如果它是一個UNIX結束的文本文件,使用

F = f.split( 「\ n」)

將字符串轉換爲列表,然後可以循環通過它行。

1

你放在這條線在錯誤的地方:

good_data = True 

一旦它被設置爲false,也不會再是真實的。

你可以這樣寫:

l = ["ch=GL000219.1", "ch=GL000320.1"] 
flag = False                   

with open('file.txt', 'r') as f, open('outfile.txt', 'w') as outfile:                     
    for line in f:                 
     if line.strip().startswith("fixedStep"):          
      flag = all(i not in line for i in l)          
     if flag:                  
      outfile.write(line)  
+0

它刪除標識符下面的每一行,甚至我感興趣的那些 – john

+0

@john你是什麼意思的「刪除每一行」,我不明白! – gushitong

+0

每個標識符都有一些下面的行(如示例)。我想刪除一些我不感興趣的標識符和以下幾行。確實也有一些我感興趣的標識符,我希望它們和它們下面的相應行。像例子 – john