Inline sed and inline perl modes are actually opening a temporary file in write mode and then copy al the lines that you wanted into the temporary file filtering out the ones that you don't want and then moving the new file in place of the old one:
$ sed -i '/localhost/d' /etc/hosts
sed: couldn't open temporary file /etc/sed1awUIL: Permission denied
As you can see I cannot modify /etc/hosts because it is owned by root and therefore I cannot modify it. Just a demonstration that sed is creating a new temporary file.
The way you can do this in python is to:
1) open original file in read mode
2) open a temp file in write mode
3) loop through all the lines in original file and write the ones you want into your temp file
4) close both file handles
5) move your temp file in place of your original file
In your case you just need a variable that counts how may lines you have alreadfy read in order to write only the ones you want into your temp file.