根据Python中倒数第二列中的值删除行

时间:2017-07-19 17:07:54

标签: python python-3.x

所以我有一个文本文件需要根据最后一列中的值进行修剪 - 如果它显示为1,则删除该行,如果为0,则保留该行。

文本看起来像这样,它只有几千行:

          #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)

提前谢谢你,这让我很生气。

1 个答案:

答案 0 :(得分: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时,这将写入你的行。否则,它将不会被写入。