[Tutor] Search and Replace
Remco Gerlich
scarblac@pino.selwerd.nl
Thu, 28 Jun 2001 09:05:00 +0200
On 0, VanL <van@lindbergs.org> wrote:
> This, once again, truncates the file and then writes it out. I am
> worried about possible data loss; Ideally, I would
> open the file for reading and writing, read in one line, change it,
> write it back out, read another line, etc. That way, if the script was
> stopped halfway through execution, the replacement wouldn't be finished,
> but the file contents would not be lost.
That won't work if the two strings don't have the same length.
It would be easier to write a temporary file, when that is done, remove the
old one and rename the temp file.
The fileinput module can do something similar: it can move the file to a
backup name, give you its contents line by line, and anything you print will
go to the old filename. It works like this:
import fileinput
def replace_in_file(filename, oldstring, newstring):
for line in fileinput.input(filename, inplace=1, backup='.bak'):
print line.replace(oldstring, newstring)
--
Remco Gerlich