user2332502
user2332502

Reputation: 3

Read numeric value from txt. file and compare it to condition Python

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.

Upvotes: 0

Views: 3225

Answers (2)

Cody Piersall
Cody Piersall

Reputation: 8557

When you read from a text file, you get strings. A string compared to an int will always evaluate to False. Instead of

str = fo.readline()

which stores a string type in str, do

str = int(fo.readline())

but be warned that if the line contains a value that cannot be an int, you will get an error.

As an aside, you do not need to put semicolons after any of the lines in your code, and the variable name str should be avoided, because it is a Python built-in type.

Upvotes: 0

mgilson
mgilson

Reputation: 310069

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.

Upvotes: 2

Related Questions