Python 2.7 使用Python删除文件中的行

Python 2.7 使用Python删除文件中的行,python-2.7,file-handling,delete-row,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

我的输入文件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仍存在于输出中。有什么想法吗???

你需要改变你的状态-现在的状态检查整条线是否等于41640。相反,每行都等于您正在读取的整行数据,后跟一个\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)
要删除多行,您可以将所有行与列表理解结合使用,如中所述

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

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

此外,由于Python的特性,您的原始条件将始终计算为True。那是因为即使是41640=行为false,将\n添加到该行中,并在转换后解释为True。基本上是首先计算,而不是后跟!=的字符串串联

>很可能是重复的……它的工作原理……以及如何施加更多的数字也被删除?”阿扎姆编辑,考虑看引用的帖子和另一个变种的方法,任何。它们会派上用场的。再次谢谢。两个建议都设法得到了答案。
del_list = ["41615", "41640", "42334"]