replace string in a file

U

Unknown

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 :)
 
A

andrei.avk

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 :)

What you want to do is either 1. load everything up into a string,
replace
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
file,
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
think
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
than
that, I'm sure someone can explain this much better, but you're far
better
off with using one of the 2 methods above.. HTH, -ak
 
U

Unknown

Thanks, andrei. I'll try that.

Le Sat, 15 Mar 2008 14:25:21 -0700, andrei.avk a écrit :
 
J

joep

you can also use standard module fileinput.input with ''inplace''
option which backs up original file automatically.

from python help for fileinput:

Optional in-place filtering: if the keyword argument inplace=1 is
passed to input() or to the FileInput constructor, the file is moved
to a backup file and standard output is directed to the input file (if
a file of the same name as the backup file already exists, it will be
replaced silently).
 
U

Unknown

Le Sat, 15 Mar 2008 16:55:45 -0700, joep a écrit :
you can also use standard module fileinput.input with ''inplace'' option
which backs up original file automatically.

from python help for fileinput:

Optional in-place filtering: if the keyword argument inplace=1 is passed
to input() or to the FileInput constructor, the file is moved to a
backup file and standard output is directed to the input file (if a file
of the same name as the backup file already exists, it will be replaced
silently).

Thanks for the idea :)
What I do not get is how I can replace a string with that.

If I write something like:

for line in filehandle.input('myfile.txt', inplace=1):
rx = re.match(r'^\s*(\d+).*',line )
if not rx:
continue
else:
oldValue = rx.group(1)
Value = 123456789
line = string.replace(line, oldValue, "%d" Value)
print line
break

This code replaces the whole file with line, instead of replacinf the old
value with the new one. Did I forget something ?
 
S

sturlamolden

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.
 
J

joep

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
 
C

cantabile

Le Mon, 17 Mar 2008 09:03:07 -0700, joep a écrit :
An example: looks for all 'junk*.txt' files in current directory and
replaces in each line the string 'old' by the string 'new'
Josef

Works like a charm. Many thanks for the example Josef :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,172
Messages
2,570,934
Members
47,477
Latest member
ColumbusMa

Latest Threads

Top