[Tutor] help on string replacement in a file
klappnase
klappnase@freenet.de
Wed Aug 6 06:07:02 EDT 2003
On Wed, 06 Aug 2003 12:22:34 +0800
"kamariah lamim" <klhjhm@hotmail.com> wrote:
> Hi.
> I wrote a function to replace a string in a file.I used built-in replace(
> ) to do that . However it failed to overwrite the old content of file with
> the new one. . Could someone trace this problem.the function is something
> like this:
>
> lineseen=0
> drot='0.678'
> batchNo=1
>
> def modify5File(drot,batchNo):
> global lineSeen
> updateFile=open('disper.501','rw')
> x=updateFile.readlines()
> for everyLine in x:
> lineSeen += 1
> if lineSeen == 10:
> string.replace(everyLine,'+0.2000000000d+00',drot,1)
> else:
> pass
> updateFile.close()
>
Hi,
I am not sure about that, but I think you should use the fileinput module for that, like:
def modify5File():
for line in fileinput.input(path-to-file, inplace=1):
line = line.replace('+0.2000000000d+00', '0.678')
sys.stdout.write(line)
This should replace every '+0.2000000000d+00' in the file with '0.678' .
Best regards
Michael
More information about the Tutor
mailing list