如果文件包含某些数据,如何从文件中删除该行

时间:2015-05-23 11:09:37

标签: python file

我在python上创建了这个程序,以便在搜索文件名之前询问用户他们的名字。然后它将打印找到其名称的行号。我希望程序删除名称所在的行 - (除了最近的3行)。这可能吗?

1 个答案:

答案 0 :(得分:0)

如果您只想保留最新的内容:

from tempfile import NamedTemporaryFile
from shutil import move

def keep_three(fle):
    name = input("Please enter your name")
    with open(fle, 'r+') as f,  NamedTemporaryFile("w",dir=".", delete=False) as out:
        # find indexes for all occurrences  of the name
        indexes = [ind for ind, line in enumerate(f) if line.strip() == name]   
        # if there are less than 3 occurrences then write the name
        if len(indexes) < 3:
            f.write("{}\n".format(name))
            return 
        elif len(indexes) == 3:
            return 
        # else use the earliest indexes less than the last three
        f.seek(0) # go back to startof file
        remove = set(indexes[:len(indexes) -3])
        for ind, line in enumerate(f):
            # only write the lines we don't want to ignore
            if ind not in remove:
                out.write(line)
     # replace the original file
     move(out.name, fle)

最好使用不同的结构来保存名称,使用字典和酸洗可能是更好的选择。 你可以使用一个Counter dict来计算,但这不会给你索引,所以可能没什么用。

您还可以使用fileinput.inputinplace=True修改原始文件:

import fileinput
import sys

def keep_three(fle):   
    name = input("Please enter your name")
    with open(fle, 'r+') as f:
        indexes = [ind for ind, line in enumerate(f) if line.strip() == name]
        if len(indexes) < 3:
            f.write("{}\n".format(name))
            return
        elif len(indexes) == 3:
            return 
        remove = set(indexes[:len(indexes)-3])
        for ind, line in enumerate(fileinput.input(fle,inplace=True)):
            if ind not in remove:
                sys.stdout.write(line)

但我认为另一种存储名称的方式最好,或至少将名称分组在文件中。