Search code examples
pythoncsvparsingurllib2

insert a variable into an url


I got a CSV file with numbers and I want to insert these numbers into a specific location in an url : jus after " "value": " Here is my code :

with open('update_cases_id.csv') as p:
    for lines in p:
        uuid = lines.rstrip()

        url_POST = "www.example.com/"

        values = {}
        values['return_type'] = 'retrieval'
        values['format'] = 'TSV'
        values['size'] = '70'
        values['filters'] = '{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value": .format(uuid)}}]}'

        data = urllib.urlencode(values)

        url_final = url_POST + '?' + data

        req2 = urllib2.Request(url_final)
        req2.add_header('cookie', cookie)
        handle = urllib2.urlopen(req2)

( edited : example input : 123456-123456-987654 example output : it s data text )


Solution

  • You can do this with string formatting, this should work for you:

    # ...snip
    values['filters'] = '{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value":%s}]}' % uuid
    # snip...
    

    The %s will be replaced by the uuid by the % replacement operator:

    >>> values = {}
    >>> uuid = 1234
    >>> values['filters'] = '{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value":%s}]}' % uuid
    >>> values
    {'filters': '{"op":"and","content":[{"op":"in","content":{"field":"cases.case_id","value":1234}]}'}