【问题标题】:Deleting rows in a file using Python使用 Python 删除文件中的行
【发布时间】:2018-05-04 05:32:13
【问题描述】:

我的输入文件“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。有什么想法吗??

【问题讨论】:

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


【解决方案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 为假,\n 也会添加到其中并解释(转换后)为True。基本上,首先评估!=,而不是字符串连接后跟!=

【讨论】:

  • 太棒了..它的工作原理..以及如何强加更多的数字被删除?
  • @Azam 已编辑,请考虑查看引用的帖子和该方法的另一种变体,any()。他们派上用场了。
  • 再次感谢。设法得到了两个建议的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2016-05-12
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 2020-06-19
  • 2014-12-14
相关资源
最近更新 更多