2017-07-19 154 views
0

因此,我有一個文本文件,我需要基於最後一列中的值進行修剪 - 如果它表示1,則刪除該行,如果爲0,請保留線。基於Python中第二列最後一列的值刪除行

的文字是這樣的,它只是有數千行:

  #name  #bunch of values     #column of interest 

    00051079+4547116 00 05 10.896 +45 47 11.570    0 0 \n 
    00051079+4547117 00 05 10.896 +45 47 11.570  432 3 0 0 \n 
    00051079+4547118 00 05 10.896 +45 47 11.570 34  6 1 0 \n 

我曾經嘗試這樣做(這樣加上約一百變化):

with open("Desktop/MStars.txt") as M: 
    data = M.read() 

data = data.split('\n') 

mactivity = [row.split()[-2] for row in data] 
#name = [row.split(' ')[0] for row in data] 

#print ((mactivity)) 

with open("Desktop/MStars.txt","r") as input: 
    with open("Desktop/MStarsReduced.txt","w") as output: 
     for line in input: 
      if mactivity =="0": 
       output.write(line) 

謝謝你在前進,它讓我發瘋。

回答

0

回想一下,來自CSV閱讀器的一行是一個列表,其中每個單元格/列是另一個值。

編輯您的最後一個小代碼塊:

with open("Desktop/MStars.txt","r") as input: 
    with open("Desktop/MStarsReduced.txt","w") as output: 
     for line in input: 
      if line[-2] == 0: 
       output.write(line) 

這會寫你的線路當且僅當倒數第二個字段的值爲0,否則它不會被寫入。

相關問題