[Tutor] Replacing the string in a file

Stefan Lesicnik stefan at lsd.co.za
Fri Jan 22 09:11:27 CET 2010


> 
> vanam, 22.01.2010 07:44:
> 
> > [Query]: How to write Python string to PYTHON to that file without
> > intact of the full contents
> 
> What one would normally do is: read the file (line by line if that's
> ok in
> your case), replace the word by the new one, write the new line to a
> new
> temporary file. When done, move the new file over the old one. That
> also
> makes sure that your changes are 'atomic' (as good as it gets), i.e..
> your
> original file is still there when you encounter an error during the
> replacement run.
> 
> Stefan

heys,

I have used the fileinput module for this quiet alot. It has an inplace option which does what you want and a backup option that keeps a backup.

http://docs.python.org/library/fileinput.html
http://www.doughellmann.com/PyMOTW/fileinput/index.html

stefan (another stefan)


More information about the Tutor mailing list