Having trouble with file modes

erikcw erikwickstrom at gmail.com
Fri Nov 3 15:21:33 EST 2006


Hi all,

I've created a script that reads in a file, replaces some data (regex),
then writes the new data back to the file.

At first I was convinced that "w+" was the tool for the job.  But now
I'm finding that the contents of the file are deleted (so I can't read
the data in).

f = open('_i_defines.php', 'w+')
data = f.read()
#patterns removed for brevity.
patterns = [(tuples)(blah blah)]

#loop through patterns list and find/replace data
for o, r in patterns:
    data = data.replace(o, r)
    print "Replaced %s with %s" % (o, r)
f.write(data)
f.close()

This results in an empty file.  All of the modes I've tried either
produce an empty file or append the data onto the end of the file.  How
Can I:

Open
Read
Truncate
...process data....
Write
Close

Do I need to open and close the file twice? (once in 'r' and then again
in 'w')

Thanks!
Erik




More information about the Python-list mailing list