[Tutor] Search and Replace

VanL van@lindbergs.org
Thu, 28 Jun 2001 01:00:37 -0600


Hello,  tahks for the comments.

Roeland Rengelink wrote:

>
>Why use regular expressions, when there is a perfectly good
>string.replace() function that does exactly what you want?
>
Because using regexes makes it a bit more general, and because (in this 
case) I needed to match a regex.
I am thinking of rewriting and expanding this to include a mode 
argument, with modes 0,1,2 = string replacement, regex, compiled regex 
object.

>I think the biggest nono in this script, is silently catching all
>errors. You will never notice anything going wrong (undefined listonly
>and skipexts, for example, but also erorrs in opening, reading and
>writing files)
>
>At least do something like:
>except:
>    debug('An error occured, ignoring...')
>
Good idea.  Thnx.

>My version
>
[snip]

Thanks for letting me see how another person did it.  It is a good idea 
to only change the file if it needs changing.  But I notice that you do 
the same sort of thying that worried me about mine:


                if changed:
                        print 'Updating :', filename
                        f = open(filename, 'w')
                        f.writelines(new_lines)

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.

>
>Hope this helps,
>
>Roeland
>
Once again, Thanks!

Van