Eric1989
Eric1989

Reputation: 639

Search, delete and output to a newly created file

I wish to create a function that will search each line of a input file, search through each line of this file looking for a particular string sequence and if it finds it, delete the whole line from the input file and output this line into a newly created text file with a similar format.

The input files format is always like so:

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

etc...

I want it so this file is input, then search for the DOB (19111991) and if it finds this string in the line then delete it from the input file and finally dump it into a new .txt document .

I'm pretty clueless if I'm being honest but I guess this would be my logically attempt even though some of the code may be wrong:

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')

Any help would be great.

Upvotes: 0

Views: 79

Answers (1)

Anshul Goyal
Anshul Goyal

Reputation: 76927

Try this code instead:

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)

Upvotes: 1

Related Questions