1

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()
Van Peer
  • 2,127
  • 2
  • 25
  • 35
rockboiler
  • 13
  • 2
  • 1
    The condition `not "Ben"` will always evaluate to `False`. It takes the string "Ben" and converts it to a `bool`, resulting in `True`, since the string is non-empty; `not` results in the negation of `True`, yielding `False`. – Sven Marnach Oct 17 '17 at 11:19

2 Answers2

2

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()
Mr. Nun.
  • 775
  • 11
  • 29
  • 1
    This is usually written as `"Ben" not in line` in Python. It's completely equivalent, but is more similar to English when read. – Sven Marnach Oct 17 '17 at 11:17
0
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()
Van Peer
  • 2,127
  • 2
  • 25
  • 35