On 9/27/06, Dave S <[EMAIL PROTECTED]> wrote:
Hi,

I am trying to read in an ascii text file, do some alterations and write it
back.

file = open(self.config.get('pdf','cert') + '/cert.pdf' , 'r+')
lines = file.readlines()

... process lines ...

file.writelines(lines)
file.close()

works but ends up appending a second modified copy to the original ... as per
the python ref.

You need to add a file.rewind() or file.seek(0) before you start writing.

Am I right in thinking that the only way is to open with a 'r', close them
open with a 'w' ?

It is not the only way.  In fact, it is not the best way.  It is actually unsafe.  What you will want to do is write to a temporary file and then replace the existing file with the temporary file.

file = open(self.config.get('pdf','cert') + '/cert.pdf' , 'r')
lines = file.readlines()
... process lines ...
outfile = open(self.config.get('pdf', 'cert') + '/cert.pdf.tmp', 'w')
outfile.writelines (lines)
outfile.close()
file.close()
os.rename(self.config.get('pdf', 'cert') + '/cert.pdf.tmp',
                self.config.get('pdf', 'cert') + '/cert.pdf')

The reason this is unsafe is two fold.
1. If the is a problem during execution, the original file is untouched.
2. With r+ or a+, if the new contents is shorter than the written file, then you might have additional data following the new contents.

Cheers

Dave


  -Arcege
--
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to