473,326 Members | 2,680 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

find, replace and save string in ascii file

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
5 3372
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: hokieghal99 | last post by:
import os, string print " " setpath = raw_input("Enter the path: ") def find_replace(setpath): for root, dirs, files in os.walk(setpath): fname = files for fname in files: find =...
2
by: gnv | last post by:
Hi all, I am writing a cross-browser(i.e. 6 and netscape 7.1) javascript program to save an XML file to local file system. I have an xml string like below: var xmlStr = "<?xml version="1.0"...
2
by: Daniel | last post by:
I use an Access database to basically take data exports, import them, manipulate the data, and then turn them into exportable reports. I do this using numerous macros, and queries to get the data...
4
by: Vic | last post by:
Hi, With VBA code from MSAccess, how to search for a string in another text file, and replace it with space and then save it under the same name? Your help is greatly appreciated. Rgds
25
by: Neo Geshel | last post by:
This works: <form> <asp:TextBox id="name" /> <%= name.ClientID %> </form> But this DOES NOT work: <form>
0
by: Xah Lee | last post by:
Interactive Find and Replace String Patterns on Multiple Files Xah Lee, 2006-06 Suppose you need to do find and replace of a string pattern, for all files in a directory. However, you do not...
2
by: John Nagle | last post by:
I'm trying to clean up a bad ASCII string, one read from a web page that is supposedly in the ASCII character set but has some characters above 127. And I get this: File...
10
by: Samuel Karl Peterson | last post by:
Greetings Pythonistas. I have recently discovered a strange anomoly with string.replace. It seemingly, randomly does not deal with characters of ordinal value 127. I ran into this problem while...
3
by: mouac01 | last post by:
Newbie here. How do I do a find and replace in a binary file? I need to read in a binary file then replace a string "ABC" with another string "XYZ" then write to a new file. Find string is the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.