parse a file for a line with specific text, then logic to determine next steps
Question: I am trying to scan a textfile for a specific keyword. When this keyword is
found there's a numeric value on the line that I need to compare to see if
it's less than a set value. If it is, the following lines in the file need to
be printed/saved until the next keyword is reached. I hope this makes sense.

Example of the textfile:

    
    
    "saleAmount","500",
    text text text
    etc etc etc
    text text text
    "saleAmount","1200",
    text text text
    etc etc etc
    text text text
    

My python file is as follows:

    
    
    import re
    info = open("results.txt", "r")
    for line in info:
        if re.match("(.*)saleAmount(.*)", line):
            for s in line:
                result=re.findall('\d+', s)
                if (result < 1000)
                    print (result)
    

In this case the line with the amount of 500 should be compared to 1000 and
printed, as should the following 2 lines. The line with the amount of 1200 and
it's following lines will be ignored.

I can get this to print out the values in a weird one digit a line result but
when I add in the comparison I can't get that.

I'm sure this is simple but I'm new to python. Thanks


Answer: Here's one possible solution:

    
    
    import re
    
    ls=[]
    
    with open('results.txt') as f:
        for line in f:
            if "saleAmount" in line:
                ls.append(line.strip('\n'))
    
    for num in range(len(ls)):
        for amnt in re.findall('\d+',ls[num]):
            if int(amnt) < 1000:
                print(amnt)
    

What I did is added the file that contain `saleAmount` to a list `ls`, then
extracted the numbers and from that list and compared to see if they are less
than 1000.

In your case, `result` is obtaining the values whether it contains a number
(splits up that number into single digit) or if it contains a string (becomes
empty list).

In your original code, try `print(result)` right after you define it without
the `if` statement and what's below it. Then you'll get a clearer
understanding as to why you can't compare it to 1000

Edit: Include "saleAmount" and following lines

    
    
    import re
    
    ls=[]
    
    with open('data.csv') as f:
        for line in f:
            ls.append(line)
    
    for w in ls:
        if "saleAmount" in w and int(re.findall('\d+',w)[0]) < 1000:
            print(w)
            for i in range(1,4):
                print(ls[ls.index(w)+i])
    

