Python:使用某些标准从文件中删除行

2024-05-29 11:24:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用某些条件从文件中删除行,但当我运行脚本时,它只会删除整个文件。当我将脚本更改为只“读取”行时,它返回带有搜索条件的行,但当我以“写入”模式打开文件时,它将从打印每行更改为删除每行,它将清空整个内容。你知道吗

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

Tags: 文件in脚本内容inputraw模式条件
2条回答

我希望你想删除有特定标准的行。您只需使用创建另一个文件,并在该文件中写入内容,如下所示:

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的行上的文件。您可能希望创建一个具有不同名称的新文件,并在程序结束时重命名它。你知道吗

相关问题 更多 >

    热门问题