Having trouble with file modes

Fredrik Lundh fredrik at pythonware.com
Sat Nov 4 08:39:17 CET 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 

"w+" means truncate first, update then:

 >>> f = open("foo.txt", "r")
 >>> f.read()
 >>> f.close()

 >>> f = open("foo.txt", "r+")
 >>> f.read()
 >>> 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


     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.


More information about the Python-list mailing list