搜索,删除并输出到新创建的文件

时间:2014-09-18 10:11:39

标签: python file line lines

我希望创建一个函数来搜索输入文件的每一行,搜索该文件的每一行,查找特定的字符串序列,如果找到它,从输入文件中删除整行并输出该行到具有类似格式的新创建的文本文件中。

输入文件格式总是这样:

Firstname:DOB
Firstname:DOB
Firstname:DOB
Firstname:DOB

等...

我想要它,所以输入这个文件,然后搜索DOB(19111991),如果它在行中找到这个字符串,则从输入文件中删除它,最后将其转储到新的.txt文档中。

如果我是诚实的话,我很无能,但我想这可能是我的逻辑尝试,即使某些代码可能是错误的:

def snipper(iFile)
    with open(iFile, "a") as iFile:
    lines = iFile.readlines()
    for line in lines:
        string = line.split(':')
        if string[1] == "19111991":
            iFile.strip_line()
            with open("newfile.txt", "w") as oFile:
                iFile.write(string[0] + ':' + '19 November' + '\n')

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

请尝试使用此代码:

def snipper(filename)
    with open(filename, "r") as f:
        lines = f.readlines()

    new_data = filter(lambda x: "19111991" in x, lines)
    remaining_old_data = filter(lambda x: "19111991" not in x, lines)

    with open("newfile.txt", "w") as oFile:
        for line in new_data:
            oFile.write(line.replace("19111991", "19th November 1991'"))

    with open(filename, "w") as iFile:
        for line in remaining_old_data:
            iFile.write(line)