繁体   English   中英

Python:使用特定条件从文件中删除行

[英]Python: Deleting lines from a file with certain criteria

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

#!/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()

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

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)

从文档:

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的行上截断文件。 您可能想要创建一个具有不同名称的新文件,并在程序末尾对其重命名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM