find, replace and save string in ascii file

Discussion in 'Python' started by peter, Aug 23, 2006.

  1. peter

    peter Guest

    Hello all,

    I'm looking for an advice.

    Example (one block in ascii file):

    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

    BackupNamFile = 1
    if BackupNamFile == 1:
    for line in NamFileOpen:
    LineTextFound1 = line.find("bk")
    LineTextFound2 = line.find("_results")
    if LineTextFound1 != -1 and LineTextFound2 != -1:
    print "Line: \t\t\t"+ str(LineNum)
    print "Request Name: \t\t"+ ReqName
    LineNumQuantity = LineNum + 2
    if LineNum == LineNumQuantity:
    print "Quantity Type: \t\t"+QuantityName
    if QuantityName == "dx":
    Suffix = "_disp"
    elif QuantityName == "vx":
    Suffix = "_velo"
    elif QuantityName == "fx":
    Suffix = "_force"
    Suffix = "_results"
    print "Suffix: \t\t"+Suffix
    print "New Request Name: \t"+NewReqName
    print "-----------------------"
    LineNum = LineNum+1
    print LineNumArray
    print len(LineNumArray)

    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
    print Temp
    peter, Aug 23, 2006
    1. Advertisements

  2. peter

    Amit Khemka Guest

    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.


    Amit Khemka, Aug 23, 2006
    1. Advertisements

  3. peter

    peter Guest

    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.
    peter, Aug 23, 2006
  4. peter

    Andy Terrel Guest

    Take your code, pretend it is in file:


    a python functions could be:

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

    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.
    Andy Terrel, Aug 23, 2006
  5. 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!
    Gabriel Genellina, Aug 23, 2006
  6. 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 = line.replace("ALFA", "BETA%s" % code)

    Roberto Bonvallet, Aug 23, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.