Having trouble with file modes

Fredrik Lundh fredrik at pythonware.com
Sat Nov 4 02:39:17 EST 2006


erikcw wrote:

> To make it write over the data, I ended up adding, which seems to work
> fine.
> 
> f = open('_i_defines.php', 'w+')

that doesn't work; you need to use "r+" if you want to keep the original 
contents.

"w+" means truncate first, update then:

 >>> f = open("foo.txt", "r")
 >>> f.read()
'hello\n'
 >>> f.close()

 >>> f = open("foo.txt", "r+")
 >>> f.read()
'hello\n'
 >>> f.close()

 >>> f = open("foo.txt", "w+")
 >>> f.read()
''

the standard approach when updating text files is to create a *new* 
file, though:

     fi = open(infile)
     fo = open(infile + ".tmp", "w")

     filter fi to fo

     fo.close()
     fi.close()

     if os.path.exists(infile + ".bak")
         os.remove(infile + ".bak")
     os.rename(infile, infile + ".bak")
     os.rename(infile + ".tmp", infile)

this leaves the old file around with a .bak extension, which is nice
if something goes wrong during filtering.

</F>




More information about the Python-list mailing list