[Tutor] help on string replacement in a file

Rodrigues op73418@mail.telepac.pt
Wed Aug 6 08:47:30 EDT 2003


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> kamariah lamim
> Sent: quarta-feira, 6 de Agosto de 2003 5:23
> To: tutor@python.org
> Subject: [Tutor] help on string replacement in a file
>
>
> 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()

Here, you read the contents of updateFile *into memory* as a list of
lines.

> 	for everyLine in x:
> 		lineSeen += 1
> 		if lineSeen == 10:
>
> string.replace(everyLine,'+0.2000000000d+00',drot,1)
> 		else:
> 			pass

Here, you replace the offending lines with new ones, but *only* in
your in-memory list of lines.

> 	updateFile.close()
>

Here, you close the file.

You forgot to write everything back to the file *in disk*.

Hope that gives you a start, with my best regards,
G. Rodrigues





More information about the Tutor mailing list