Removing last line while appending to file
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.
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]
guff = f.read(taglen)
for k in range(3):
f.write("added %d%s" % (k, outsep))
f.write(tag + outsep)
if __name__ == "__main__":
More information about the Python-list