hahobson hahobson - 9 months ago 42
Python Question

Using urllib2 to download text to be used to evaluate a variable

Am downloading a text page, c.txt, from a webserver. c.txt only contains the letter 'c' . Able to download file fine and print its contents, the character 'c'. Cannot, however, use its contents in the code below:

import urllib2

req = urllib2.Request('http://localhost/c.txt')
response = urllib2.urlopen(req)
result = str(response.read())
print(result) # prints 'c' just fine
furl = "c"
furl = str(furl)
if result == furl: # Does not work

No errors are incurred. Just will not work


There is most likely an extra white space character in the result. You can check for it by printing characters on either side.

print '>%s<' % result

If the result looks like >c < you've got a trailing white space.

To remove the leading and trailing white space from a string, you can use the strip() method on the string.

result = str(response.read()).strip()

Or you can do it right at the point of comparison.

if result.strip() == furl:
    print 'correct'