This "answer" is for the lyre ... I will correct my previous comment: if the needle is in the first three lines of the file, your script will either raise an IndexError or gain access to the line. Access to them, sometimes with interesting side effects.
An example of your script calling IndexError:
>>> lines = "@string line 0\nblah blah\n".splitlines(True) >>> needle = "@string " >>> for i,line in enumerate(lines): ... if line.startswith(needle) and lines[i-3].startswith(needle): ... lines[i-3] = lines[i-3].replace(needle, "") ... Traceback (most recent call last): File "<stdin>", line 2, in <module> IndexError: list index out of range
and this example shows not only that the Earth is round, but also why your "fix" of the problem "not to delete the entire line" should use .replace(needle, "", 1) or [len(needle):] instead of .replace(needle, "")
>>> lines = "NEEDLE x NEEDLE y\nnoddle\nnuddle\n".splitlines(True) >>> needle = "NEEDLE" >>> # Expected result: no change to the file ... for i,line in enumerate(lines): ... if line.startswith(needle) and lines[i-3].startswith(needle): ... lines[i-3] = lines[i-3].replace(needle, "") ... >>> print ''.join(lines) xy <<<=== whoops! noddle nuddle <<<=== still got unwanted newline in here >>>
John machin
source share