[Tutor] Replacing the string in a file

Shashwat Anand anand.shashwat at gmail.com
Fri Jan 22 08:49:59 CET 2010


Editing original file can be risky at times. If @vanam wants to edit the
same fie, he can open the original file, read it, rename it to say
'data.txt.bak' and then write the modified content to the file named as
'data.txt'. This way he gets the data in the file he wants and also have a
backup of original file.

On Fri, Jan 22, 2010 at 1:07 PM, Stefan Behnel <stefan_ml at behnel.de> wrote:

> 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
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100122/dec2f29d/attachment-0001.htm>


More information about the Tutor mailing list