What do you guys think about this - file writing

laotseu bdesth at nospam.free.fr
Sat Aug 31 12:38:34 EDT 2002


Micah Mayo wrote:
> I'm trying to write a script that looks for a string in a textfile and 
> replaces it with a given string. This is what I've come up with:
> 
> #!/usr/local/bin/python
> import os
> orig = 'sendmail_enable="YES"'
> pref = 'sendmail_enable="NONE"\n'
> 
> tmp = file('rc.conf.tmp','w')
> for eachLine in open('rc.conf'):
> 
>     print orig,'\n',eachLine
>     if eachLine.find(orig) !=-1:
>         print '..replacing', orig, 'with',pref
>         tmp.writelines(pref)
>         # will add code to replace eachLine w/ pref later
> 
>     else:
>         print 'skipping'
>         tmp.write(eachLine)
> 
> 
> tmp.close()
> os.rename('rc.conf.tmp','rc.conf')
> 
> This works - but I was hopeing there was a more elegant way to do this. 
> If anyone can think of a more efficient way to do this(not having to 
> open two files would be nice), I'd appreciate the input.
> 
> Thnx
> Micah
> 



AFAIK, working with two files is the standard and perhaps safer way when 
it comes to this.

laotseu




More information about the Python-list mailing list