1

What my text is

$TITLE = XXXX YYYY
1 $SUBTITLE= XXXX YYYY ANSA
2 $LABEL = first label
3 $DISPLACEMENTS
4 $MAGNITUDE-PHASE OUTPUT
5 $SUBCASE ID = 30411

What i want

$TITLE = XXXX YYYY
1 $SUBTITLE= XXXX YYYY ANSA
2 $LABEL = new label
3 $DISPLACEMENTS
4 $MAGNITUDE-PHASE OUTPUT
5 $SUBCASE ID = 30411

The code i am using

import re
fo=open("test5.txt", "r+")
num_lines = sum(1 for line in open('test5.txt'))
count=1
while (count <= num_lines):
    line1=fo.readline()
    j= line1[17  : 72]
    j1=re.findall('\d+', j)
    k=map(int,j1)       
    if (k==[30411]):
        count1=count-4
        line2=fo.readlines()[count1]
        r1=line2[10:72]  
        r11=str(r1)
        r2="new label"
        r22=str(r2)
        newdata = line2.replace(r11,r22)
        f1 = open("output7.txt",'a')
        lines=f1.writelines(newdata)
    else:
        f1 = open("output7.txt",'a')
        lines=f1.writelines(line1)
    count=count+1

The problem is in the writing of line. Once 30411 is searched and then it has to go 3 lines back and change the label to new one. The new output text should have all the lines same as before except label line. But it is not writing properly. Can anyone help?

3
  • Does the line literally say 2 $LABEL or is $LABEL a proxy for whatever is in the file? Commented Jul 6, 2016 at 15:06
  • 1
    It most likely literally does.This is some kind of FEM output control file. But OP is trying to go from London to NY through South Africa. Commented Jul 6, 2016 at 15:08
  • The problem is that after searching for the subase..it has to write a new label three lines back. The output i have is writing it at the same location i.e. on the last line. I cant seem to think of a different approach. Commented Jul 8, 2016 at 17:21

1 Answer 1

1

Apart from many blood-curdling but noncritical problems, you are calling readlines() in the middle of an iteration using readline(), causing you to read lines not from the beginning of the file but from the current position of the fo handle, i.e. after the line containing 30411. You need to open the input file again with a separate handle or (better) store the last 4 lines in memory instead of rereading the one you need to change.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.