What do you guys think about this - file writing

Micah Mayo astrophels at yahoo.com
Sat Aug 31 02:54:16 CEST 2002


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




More information about the Python-list mailing list