How to update a specific line in a file in python?

468 Views Asked by At

I am trying to create a program which can update a file. I created a test program as I cannot figure out how to update a part of the file.

I want to make it so that if a name matches that of one in the file, it will delete the one name and its data and place the name and new data at the end.

Here is my code where I am simply trying to remove the name from the list:

lines = open("input.txt", "rt")
output = open("output.txt", "wt")
for line in lines:
    if not "Ben":
        output.write(line+"\n")
lines.close()
output.close()
2

There are 2 best solutions below

1
Mr. Nun. On BEST ANSWER

looks like you just need to fix your condition:

lines = open("input.txt", "rt")
output = open("output.txt", "wt")
for line in lines:
    if "Ben" not in line:
        output.write(line+"\n")
lines.close()
output.close()
1
Van Peer On
lines = open("input.txt", "rt")
output = open("output.txt", "wt")
for line in lines:
    if not "Ben" in line:
        output.write(line+"\n")
    else:
        output.write(line.replace("Ben","replace/delete Ben")+"\n")
lines.close()
output.close()