By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,846 Members | 2,107 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,846 IT Pros & Developers. It's quick & easy.

find, replace and save string in ascii file

P: n/a
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",".n am.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()

Aug 23 '06 #1
Share this Question
Share on Google+
5 Replies


P: n/a
On 23 Aug 2006 05:48:37 -0700, peter <bo*****@gmail.comwrote:
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.
Aug 23 '06 #2

P: n/a
Thank you for your advice.

I'm not so good in python yet, so could you be so kind and write me a
piece of code for the part

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

Because that's what I don't know how to do it. How to replace a string
in the middle of the file and than save this file.

Thanks a lot.
Amit Khemka wrote:
On 23 Aug 2006 05:48:37 -0700, peter <bo*****@gmail.comwrote:
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.
Aug 23 '06 #3

P: n/a
Take your code, pretend it is in file:

$------------------------
NAME='ALFA'
CODE='x'
$------------------------
a python functions could be:

def change(filename):
fp = open(filename, 'r')
lines = fp.readlines()
fp.close()
for i in range(len(lines)):
if lines[i].find('NAME') >= 0:
if lines[i+1].find('CODE') >= 0:
code = lines[i+1].split('=')[1]
lines[i] = 'NAME='+<something based off code>
fp2 = open(filename,'w')
fp2.write("".join(lines))

So this is pretty crude and not very robust. But should give you about
some idea of how to write something. I'm not sure if there is a way
around opening two file pointers but I think python has no problems
with this. Also if you files can't fit into memory you probably want
to do something a lot more, that is read only a block at a time and
then mess with stuff, probably writing out to a temp file and then
overwriting your original file.
peter wrote:
Thank you for your advice.

I'm not so good in python yet, so could you be so kind and write me a
piece of code for the part

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

Because that's what I don't know how to do it. How to replace a string
in the middle of the file and than save this file.

Thanks a lot.
Amit Khemka wrote:
On 23 Aug 2006 05:48:37 -0700, peter <bo*****@gmail.comwrote:
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.
Aug 23 '06 #4

P: n/a
At Wednesday 23/8/2006 09:48, peter wrote:
>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....
Better create a new file with the new contents, and then rename it.

Gabriel Genellina
Softlab SRL

__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 23 '06 #5

P: n/a
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
Aug 23 '06 #6

This discussion thread is closed

Replies have been disabled for this discussion.