user3884909 user3884909 - 1 month ago 9
Python Question

If statements returning wrong data

I have some code similar to this: It goes though a list and queries an API to check if it returns a JSON object:

for one in many:
print "Checking "+one
url = "http://an.api/"+one
contents = urllib2.urlopen(url)
print len(contents.read()) > 10
if len(contents.read()) > 10:
print "online"
else:
print "offline"


If JSON is returned, the user is online, if not he is offline. Running the script returns something similar to this:

Checking a
True
offline
Checking b
True
offline
Checking c
False
offline


It says "True", but why does it print "offline"?

Answer

You need to save off the read, if you are going to perform multiple operations on the output

for one in many:   
    print "Checking "+one
    url = "http://an.api/"+one
    contents = urllib2.urlopen(url)
    myData = contents.read()
    print len(myData) > 10
    if len(myData) > 10:
        print "online"
    else:
        print "offline"