Removing last line while appending to file

John Machin sjmachin at
Wed Apr 30 23:03:27 CEST 2003

Peter Hansen <peter at> wrote in message news:<3EAFB754.41CE2258 at>...
> Tim Wegener wrote:
> > 
> > Someone emailed me directly with the solution: use open(filename, "r+")
> > This solved my problem.
> > (I was using the wrong mode for open())
> Maybe mode "rb+" would be a little better for you, if these needs
> to be used on Windows or to be portable to Windows.

Generally seeking is very dodgy in text mode, but it *seems* to work
in this case on Windows (2000). Using binary mode to create files that
need to be read as text files by other software is a programming
nuisance -- see "outsep" in the following short script which attempts
to be portable and demonstrates using text or binary mode. Works OK on
Windows 2000. Not tested on any other OS.

import os, sys
tag = "</log>"
taglen = len(tag)
def add_lines(fname, bin=1):
   f = file(fname, ["r+", "rb+"][bin])
   outsep = ["\n", os.linesep][bin], 2)
   guff =
   print repr(guff), 1)
   for k in range(3):
      f.write("added %d%s" % (k, outsep))
   f.write(tag + outsep)
if __name__ == "__main__":
   add_lines(sys.argv[1], int(sys.argv[2]))

More information about the Python-list mailing list