使用Python删除文件中的行

时间:2018-05-04 05:32:14

标签: python-2.7 file-handling delete-row

我有输入文件“input.dat”包含一些像这样的值:

41611   2014    12  18  0   0
41615   2014    12  18  0   0
41625   2014    12  18  0   0
41640   2014    6   14  3   3
42248   2014    12  18  0   0
42323   2014    12  18  0   0
42330   2014    8   13  7   7
42334   2014    12  18  0   0
42335   2014    12  18  0   0
...

我有很多数据集文件但似乎有太多不需要的数据 如何为此案例41640和42330删除许多行及其整个行值。现在我使用了这个脚本:

with open(path+fname,"r") as input:
    with open("00-new.dat","wb") as output: 
        for line in input:
            if line!="41640"+"\n":
                output.write(line)

结果:数据41640仍然存在于输出中。任何想法??

1 个答案:

答案 0 :(得分:1)

你需要改变你的状况 - 它现在如何检查整行是否等于41640。相反,每个line等于您正在阅读的整行数据,后跟\n。您的程序的固定版本如下所示:

with open("00-old.dat","r") as input:
with open("00-new.dat","wb") as output:
    for line in input:
        if "41640" not in line:
            output.write(line)

要删除多行,您可以使用all()结合列表推导,例如this post中所述,

if all(nb not in line for nb in del_list):
    output.write(line)

其中del_list是您要删除的值列表,

del_list = ["41615", "41640", "42334"]

此外,由于Python operator precedence,您的原始状态将始终评估为True。这是因为即使41640!=line为false,也会将\n添加到其中并在解释后(转换后)为True。基本上,首先评估!=,而不是字符串连接,后跟!=