replace string in a file
josef.pktd at gmail.com
Mon Mar 17 17:03:07 CET 2008
On Mar 16, 10:35 pm, sturlamolden <sturlamol... at yahoo.no> wrote:
> On 15 Mar, 21:54, Unknown <cantabile... at wanadoo.fr> wrote:
> > 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?
> A file is a stream of bytes, not a list of lines. You can't just
> replace a line with another, unless they have the exact same length.
> You must rewrite the whole file to get it right.
An example: looks for all 'junk*.txt' files in current directory and
replaces in each line the string 'old' by the string 'new'
import os, glob, fileinput
allfiles = glob.glob(os.getcwd() + '\\junk*.txt') # makes absolute
findstr = 'old'
replstr = 'new'
countlinesfound = 0
for line in fileinput.input(allfiles,inplace=1):
if line.find(findstr) != -1:
line = line.replace(findstr,replstr) # old string , new
countlinesfound += 1
print line, # this writes line back to the file
I found something similar in a tutorial when I started to learn
Python, but I don't remember which one.
More information about the Python-list