find, replace and save string in ascii file

peter borique at gmail.com
Wed Aug 23 08:48:37 EDT 2006


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....

Thanks in advance for any kind of help. Regards, Boris


import shutil

NamFile="test2.nam"
BackupNamFile = 1
if BackupNamFile == 1:
shutil.copyfile(NamFile,NamFile.replace(".nam",".nam.bak"))
LineNum=1
LineNumQuantity=0
ArrayCount=0
LineNumArray=[]
ReqArray=[]
ReqName=""
NamFileOpen=file(NamFile,"r+")
for line in NamFileOpen:
LineTextFound1 = line.find("bk")
LineTextFound2 = line.find("_results")
if LineTextFound1 != -1 and LineTextFound2 != -1:
ReqName=line.split("'")[1]
print "Line: \t\t\t"+ str(LineNum)
print "Request Name: \t\t"+ ReqName
LineNumQuantity = LineNum + 2
ReqArray=[LineNum-2,ReqName]
if LineNum == LineNumQuantity:
QuantityName=line.split("'")[1]
print "Quantity Type: \t\t"+QuantityName
if QuantityName == "dx":
Suffix = "_disp"
elif QuantityName == "vx":
Suffix = "_velo"
elif QuantityName == "fx":
Suffix = "_force"
else:
Suffix = "_results"
print "Suffix: \t\t"+Suffix
NewReqName=ReqName.replace("_results",Suffix,1)
ReqArray.append(NewReqName)
LineNumArray.insert(ArrayCount,ReqArray)
ArrayCount+=1
print "New Request Name: \t"+NewReqName
print "-----------------------"
LineNum = LineNum+1
print LineNumArray
print len(LineNumArray)
NamFileOpen.close()

NamFileOpen2=file(NamFile,"r+")
LineNum=1
for i in LineNumArray:
print i
for line in NamFileOpen2:
print line
print LineNum
print i[1]
if i[0]== LineNum:
print i[0]
print LineNum
print line
Temp=line.replace(line.split("'")[1],i[2],1)
print Temp
NamFileOpen2.write(Temp) 
LineNum=LineNum+1 
NamFileOpen2.close()




More information about the Python-list mailing list