Removing last line while appending to file

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


Peter Hansen <peter at engcorp.com> wrote in message news:<3EAFB754.41CE2258 at engcorp.com>...
> 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.

HTH,
John
8<---
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]
   f.seek(-taglen-len(os.linesep), 2)
   guff = f.read(taglen)
   print repr(guff)
   f.seek(-taglen, 1)
   for k in range(3):
      f.write("added %d%s" % (k, outsep))
   f.write(tag + outsep)
   f.close()
if __name__ == "__main__":
   add_lines(sys.argv[1], int(sys.argv[2]))
8<---




More information about the Python-list mailing list