find, replace and save string in ascii file

Roberto Bonvallet rbonvall at cern.ch
Wed Aug 23 12:26:44 EDT 2006


peter wrote:
> 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.

name = "myfile"
lines = file(name).readlines()

for i, line in enumerate(lines):
    if "ALFA" in line:
        code = lines[i + 1].split("=")[1].strip("' \n")
        lines[i] = line.replace("ALFA", "BETA%s" % code)

file(name).writelines(lines)

-- 
Roberto Bonvallet



More information about the Python-list mailing list