replace string in a file

andrei.avk at andrei.avk at
Sat Mar 15 22:25:21 CET 2008

On Mar 15, 3:54 pm, Unknown <cantabile... at> wrote:
> 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 =
>         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 :-)

What you want to do is either 1. load everything up into a string,
text, close file, reopen it with 'w' flag, write string to it. OR if
file is too big, you can read each line, replace, write to a temp
then when done move the file over the old one.

I think there are technical reasons why file-reading and iteration api
are not very suitable for reading and writing at the same time. I
you'd have to set the filepointer back one line (it can be manipulated
by giving it bytes ahead/back, so that would be difficult in itself),
then delete the line and then write new string. It may be even harder
that, I'm sure someone can explain this much better, but you're far
off with using one of the 2 methods above.. HTH, -ak

More information about the Python-list mailing list