replace string in a file

Unknown cantabile.03 at wanadoo.fr
Sat Mar 15 21:54:25 CET 2008


Hi, 
I've got this code :

cb = open("testfile", "r+")
f = cb.readlines()
for line in f:
    rx = re.match(r'^\s*(\d+).*', line)
    if not rx:
        continue
    else:
        serial = rx.group(1)
        now = time.time()
        today = time.strftime('%Y%m%d00', time.localtime(now))
        todayVal, serialVal = long(today), long(serial)
        if todayVal <= serialVal: 
	    todayVal = serialVal + 1
        else: 
            todayVal += 1
        line = string.replace(line, serial, "%d" %todayVal)
        cb.write(line + "\n")
        print 'Updated serial from "%s" to "%d"' % ( serial, todayVal )
        break      
cb.close()

I was expecting to replace the old value (serial) with the new one 
(todayVal). Instead, this code *adds* another line below the one found...

How can I just replace it?

Thanks for your help :-)



More information about the Python-list mailing list