Search code examples
python-2.5

How to edit the last few characters of a file?


I'm making a small program to trace the execution flow of a program. I have some files that have source code and some that don't. For calls that happen in files without source, I'm trying to count them and tack that number to the end of the output line.

From what I understand I'm positioning the cursor 3 characters from the end and then when I write output to myfile, it should have overwritten the previous 3 characters. But when I look in the file, those 3 characters are just getting appended to the end.

with open("C:\\Windows\\Temp\\trace.html", "a+") as myfile:
                if hasNoSource and not fileHasChanged:
                    myfile.seek(-3,2)
                    output = line
                else:
                    self.noSourceCallCount = 0
                myfile.write(output)
            return self.lineHook

Solution

  • "a+" mode is open for append mode and any changes by seek() will be reset by next write(). Use "r+" mode.