【问题标题】:Python: Deleting lines from a file with certain criteriaPython:从具有特定条件的文件中删除行
【发布时间】:2017-04-28 13:23:13
【问题描述】:

我正在尝试从具有特定条件的文件中删除行,但是当我运行脚本时,它只会删除整个文件。当我将脚本更改为仅“读取”行时,它会返回带有搜索条件的行,但是当我以“写入”模式打开文件并将其从打印每一行更改为删除每一行时,它会清空整个内容。

#!/usr/bin/env python

f = raw_input('Enter filename > ')

with open(f, 'w+') as fobj:
    criteria = raw_input('Enter criteria > ')
    for eachLine in fobj:
        if criteria in eachLine:
            fobj.remove(eachLine)
            break


fobj.close()

【问题讨论】:

  • 旁注:如果您使用的是with-语句,则不需要fobj.close()。那些把柄关在幕后。

标签: python


【解决方案1】:

我希望您想删除具有特定条件的行。您可以简单地创建另一个文件并将内容写入该文件,如下所示:

output = []
with open('test.txt', 'r') as f:
    lines = f.readlines()
    criteria = 'test'
    output =[line for line in lines if criteria not in line]


fin = open('newfile.txt', 'wb')
fin.writelines(output)

【讨论】:

  • 酷。我想我可以做到这一点,但我只是很困惑为什么我不能让它与文件一起工作。我可以对几乎任何其他可迭代但不是这个文件做同样的事情
【解决方案2】:

来自文档:

w+ Open for reading and writing.  The file is created if it does not
   exist, otherwise it is truncated.  The stream is positioned at
   the beginning of the file.
a+ Open for reading and writing.  The file is created if it does not
   exist.  The stream is positioned at the end of the file.  Subse-
   quent writes to the file will always end up at the then current
   end of file, irrespective of any intervening fseek(3) or similar.

所以您正在截断包含with open 的行上的文件。您可能希望创建一个具有不同名称的新文件并在程序结束时重命名它。

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多