[Tutor] help on string replacement in a file

kamariah lamim klhjhm at hotmail.com
Tue Aug 12 14:32:28 EDT 2003


Thank you for your code.
may i know what i does it means by inplace?

>From: klappnase <klappnase at freenet.de>
>To: tutor at python.org
>Subject: Re: [Tutor] help on  string replacement in a file
>Date: Wed, 6 Aug 2003 11:07:39 +0200
>
>On Wed, 06 Aug 2003 12:22:34 +0800
>"kamariah lamim" <klhjhm at 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
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor

_________________________________________________________________
Download the latest MSN Messenger http://messenger.msn.com.my




More information about the Tutor mailing list