find, replace and save string in ascii file

Amit Khemka khemkaamit at gmail.com
Wed Aug 23 09:28:07 EDT 2006


On 23 Aug 2006 05:48:37 -0700, peter <borique at gmail.com> wrote:
> Hello all,
>
> I'm looking for an advice.
>
> Example (one block in ascii file):
> $------------------------
> NAME='ALFA'
> CODE='x'
> $------------------------
>
> There are many similar blocks in the file with different NAMEs and
> different CODEs. What I'm looking for is a script that searchs through
> whole file and finds all strings with name ALFA and based on what CODE
> is after each ALFA (can be x, y or z) the ALFA name is replaced by
> BETAx,BETAy or BETAz and so changed file saves.
>
> What I did is that I can find all strings which I need, next I change
> these strings based on CODE, but what I can't is to replace old string
> with new one, on the same position in the file. It always writes new
> string at the end of the file. Here is my code....

A simpler way can be:

1. Read a 'block' from the input file, ( you can simply read a line
starting with 'NAME' and keep on reading till you find a line with
starting 'CODE')
2. Once you have read a 'block', make whatever you want changes to the
NAME and then write the 'block' to a temperory file.

If you want the output to be written to same file just 'move' this
temperory file to the input file once you are done.

Note: if there is other stuff in the input file, apart from such
'blocks' that you want to preserve, a small modification in step 1
would take care of it.

hth,
amit.

-- 
----
Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.



More information about the Python-list mailing list