pythonjsonurlurlliburlopen

Passing a variable in URL?


I'm new in Python. I have a file which has a bunch of ids (integer values) written in them. It's a text file.

Now I need to pass each id inside the file into a url.

For example "https://example.com/[id]"

It will be done in this way

A = json.load(urllib.urlopen("https://example.com/(the first id present in the text file)"))
print A

What this will essentially do is that it will read certain information about the id present in the above URL and display it. I want this to work in a loop format where in it will read all the ids inside the text file and pass it to the URL mentioned in 'A' and display the values continuously..is there a way to do this?


Solution

  • Old style string concatenation can be used

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

    The new style string formatting:

    >>> url = "https://example.com/{0}".format(id)
    >>> print url
    https://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()