The actual error in your way to do this was already pointed out, but instead of comparing the content of each line, I recommend you simply compare the line number or use startswith
. Otherwise you are doing a lot of unneeded string comparisons, which can be costly.
Other improvements could be to handle your file using with
, opening the file only once and allowing to delete multiple lines at once.
# 'r+' allows you to read and write to a file
with open("test.txt", "r+") as f:
# First read the file line by line
lines = f.readlines()
# Go back at the start of the file
f.seek(0)
# Filter out and rewrite lines
for line in lines:
if not line.startswith('dy'):
f.write(line)
# Truncate the remaining of the file
f.truncate()