What do you guys think about this - file writing

Gerhard Häring gerhard.haering at gmx.de
Fri Aug 30 22:05:32 EDT 2002


Micah Mayo wrote in comp.lang.python:
> 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:

TIMTOWTDI ;-)

#!/usr/bin/env python
import re

SENDMAIL_RE = re.compile("^\w*sendmail_enable\w*=\w*.*$", re.M)

f = open("/etc/rc.conf")
t = f.read()
f.close()

t =  SENDMAIL_RE.sub('sendmail_enable="NO" # Sendmail sucks - use Postfix', t)
f = open("/etc/rc.conf", "w")
f.write(t)
f.close()

> #!/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.

OTOH, your way of using a temp file looks reasonably safe, as the rename is
an atomic filesystem operation. Mine just assumes that the program doesn't
crash during open() and close() for some weird reason.

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))



More information about the Python-list mailing list