Read numeric value from txt. file and compare it to condition Python
Question: I'm new to Python and working on final project for my degree. I want to write
a Python script which will read numeric value (like: 21, 23, 28 etc.) and
compare it to value in the script. If the value matches it should execute
another python script. Everything seem to work correctly, but the red value
from file make no change in conditions matching. The script every time
executes statement ELSE instead of IF while the condition is really true.

Here is my code:

    
    
    import time
    import sys
    import os
    
    
    check_period = 2
    fo = open("/home/pi/thermometer1.txt", "r+")
    str = fo.readline();
    fo.close()
    
    
    while True:
        fo = open("/home/pi/thermometer1.txt", "r+")
        str = fo.readline();
        if str < 25 :
            os.system("python /home/pi/servo/servo1/servo6.py")
            print str
            fo.close()
        else:
            os.system("python /home/pi/servo/servo1/servo1.py")
            print str
            fo.close()
        time.sleep(check_period)
    

One more question would be how to edit this script which will compare one .txt
file with numeric value like. 23 to other .txt file with numeric value like.
27 and if condition is met execute another python script (similar like the
code above). Thanks in advance for all comments.


Answer: Reading from the file you get strings, not integers. Since they're different
(non-comparible) types, any comparison you do result in a consistent, but
arbitrary value based on the types1. Apparently, strings are considered
greater than integers (for Cpython -- Other implementations might behave
differently).

You need to construct an integer out of your string instead:

    
    
    int_from_str = int(fo.readline())
    

* * *

While we're at it, there are much better ways to iterate over a file:

    
    
    with open("/home/pi/thermometer1.txt") as fin:
        for line in fin:
            int_from_str = int(fin)
            ...
    

1On python3.x, any comparison other than `==` will raise an exception.

