Newbie question: string replace

Mike Meyer mwm at mired.org
Tue Oct 25 16:48:57 EDT 2005


"usgog at yahoo.com" <usgog at yahoo.com> writes:

> So how to overwrite the config file directly in script.py instead of
> running script.py with two params?

Don't overwrite the file directly. Save a copy, then rename it. That
way, you don't replace the new version until you know the old version
is safely written to disk, thus avoid accidently losing the data in
the file.

def modfile(filein, mod):
    fileout = filein + ' temp'
    fin = open(filein, 'r')
    fout = open(fileout, 'w')
    fout.write(mod(fin.read()))
    fin.close()
    fout.close()
    os.unlink(filein)
    os.rename(fileout, filein)

The truly paranoid will replace os.unlink(filein) with
os.rename(filein, filein + '.back').

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list