0

I have a python script that searches through a file:

this is a sample of the input text file:

String A 1
String B 1
String B 2
String B 3
String A 2
String B 4

It stores a numerical value in string A, then does some processing for each existence of a segment of string B where each segment is a different number

y=0
while y < len(InFileStr):
    if "String A" in InFileStr[y]:
        StringA = int(InFileStr[y].split("")[2])
    elif "String B" in InFileStr[y]):
        print "String B" + int(InFileStr[y].split("")[2])"\n"
    y+=1

This "should" produce:

String B 1
String B 2
String B 3
String B 4

where StringA =2 as it's overwritten

However, can't figure out how to just print

String B 1
String B 4
9
  • Are you missing a increment at the end of that while loop? Regardless, instead of using a while loop, you should probably use for line in InFileStr. Commented Feb 21, 2013 at 13:31
  • don't understand, what is the expected output? Commented Feb 21, 2013 at 13:32
  • sorry left out a y+=1 Commented Feb 21, 2013 at 13:34
  • The expected output is that we only process String B twice, not 4 times. Commented Feb 21, 2013 at 13:36
  • And, presumably, a preceding y = 0. I think we'll need some more clarification of what this is meant to do before we can be much more helpful. Commented Feb 21, 2013 at 13:37

2 Answers 2

1

Just trying to interpret what you're looking for, it seems like you just wanted to pair the closest A-string, with a B-string. In which case all you needed was a variable to keep track of the last A string, that way you know you can execute on a B-String. If this is the case, the below code should hopefully work for you.

lastLineStraingA = False

for line in infile.readlines():
    if "StringA" in line:
        lastLineStringA = True
        storeValueInLine(line)
        continue
    elif ("StringB" in line) and (True == lastLineStringA):
        process(line)

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

2 Comments

Excellent man, this works. Apologies to all for the cryptic nature of the question in the first place.
no problem. Someone had suggested I edit the post to not have the continue in the if condition. This was done intentionally to capture and correctly set the lastLine variable in the event that you had a String-C. I'm updating the (true) to (True). Since I was in C++ mode :P
0

see if this will help you

while y < len(InFileStr):
    if "String A" in InFileStr[y]:
        flag = True    
        storevalueInLine()
    elif "String B" in InFileStr[y]):
        if flag:
            process(StringB)
            flag = False
    y+=1

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.