Search code examples
pythonfilepython-3.6fileupdate

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


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

Solution

  • 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()