Your problem is that lines[5]
will always be equal to line6
. You never modified the sixth line in lines
, so line6
and lines[5]
are still equal. Thus, the condition lines[5] != line6
will always fail.
If you want to always remove the sixth line from your file, you can use enumerate
. For example:
with open("file.txt", "r") as infile:
lines = infile.readlines()
with open("file.txt", "w") as outfile:
for pos, line in enumerate(lines):
if pos != 5:
outfile.write(line)