On Mar 16, 10:35 pm, sturlamolden <[EMAIL PROTECTED]> wrote:
> On 15 Mar, 21:54, Unknown <[EMAIL PROTECTED]> 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'

<code>
import os, glob, fileinput

allfiles = glob.glob(os.getcwd() + '\\junk*.txt') # makes absolute
paths
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
string
        countlinesfound += 1
    print line,    # this writes line back to the file

print countlinesfound
</code>

I found something similar in a tutorial when I started to learn
Python, but I don't remember which one.

Josef
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to