Passing a variable in url? Passing a variable in url? json json

Passing a variable in url?


Old style string concatenation can be used

>>> id = "3333333">>> url = "https://example.com/%s" % id>>> print urlhttps://example.com/3333333>>> 

The new style string formatting:

>>> url = "https://example.com/{0}".format(id)>>> print urlhttps://example.com/3333333>>> 

The reading for file as mentioned by avasal with a small change:

f = open('file.txt', 'r')for line in f.readlines():    id = line.strip('\n')    url = "https://example.com/{0}".format(id)    urlobj = urllib.urlopen(url)    try:        json_data = json.loads(urlobj)        print json_data    except:        print urlobj.readlines()


lazy style:

url = "https://example.com/" + first_idA = json.load(urllib.urlopen(url))print A

old style:

url = "https://example.com/%s" % first_idA = json.load(urllib.urlopen(url))print A

new style 2.6+:

url = "https://example.com/{0}".format( first_id )A = json.load(urllib.urlopen(url))print A

new style 2.7+:

url = "https://example.com/{}".format( first_id )A = json.load(urllib.urlopen(url))print A


The first thing you need to do is know how to read each line from a file. First, you have to open the file; you can do this with a with statement:

with open('my-file-name.txt') as intfile:

This opens a file and stores a reference to that file in intfile, and it will automatically close the file at the end of your with block. You then need to read each line from the file; you can do that with a regular old for loop:

  for line in intfile:

This will loop through each line in the file, reading them one at a time. In your loop, you can access each line as line. All that's left is to make the request to your website using the code you gave. The one bit your missing is what's called "string interpolation", which allows you to format a string with other strings, numbers, or anything else. In your case, you'd like to put a string (the line from your file) inside another string (the URL). To do that, you use the %s flag along with the string interpolation operator, %:

url = 'http://example.com/?id=%s' % lineA = json.load(urllib.urlopen(url))print A

Putting it all together, you get:

with open('my-file-name.txt') as intfile:  for line in intfile:    url = 'http://example.com/?id=%s' % line    A = json.load(urllib.urlopen(url))    print A