0

Hope you are doing well, i have a csv file where i have 4 columns:

id,       h,      w,     x,   y
ddd:1234  52      11     22   33

and from the following link i want to replace the same attributes from the link with the ones from the csv:

www.example.com/ImagingService/imagingService?id=ddd:0104:image&coords=ddd:0104:alto&w=244&x=12&h=321&y=12

How can i replace the id,h,w,x,y from the url with the ones from the CSV?

Any help would be really appreciated.

mike.pngs
  • 15
  • 3
  • Solutions here: https://stackoverflow.com/questions/43607870/how-to-change-values-of-url-query-in-python and here: https://stackoverflow.com/questions/26221669/how-do-i-replace-a-query-with-a-new-value-in-urlparse – Rivers Feb 03 '21 at 11:35
  • 2
    Does this answer your question? [How to change values of url query in python?](https://stackoverflow.com/questions/43607870/how-to-change-values-of-url-query-in-python) – Rivers Feb 03 '21 at 11:35

1 Answers1

0

You can make use of Python DictReader to read each row of your CSV file as a dictionary. This can then be passed to urlencode which returns the correctly encoded URL to use. For example:

from urllib.parse import urlencode
import csv

with open('parameters.csv', newline='') as f_input:
    csv_input = csv.DictReader(f_input)
    
    for row in csv_input:
        url = f"https://www.example.com/ImagingService/imagingService?{urlencode(row)}"
        print(url)

So if you had a parameters.csv file which had the following:

id,h,w,x,y
ddd:1234,52,11,22,33
aaa:5678,62,44,55,66

You would get the following output:

https://www.example.com/ImagingService/imagingService?id=ddd%3A1234&h=52&w=11&x=22&y=33
https://www.example.com/ImagingService/imagingService?id=aaa%3A5678&h=62&w=44&x=55&y=66

In your example, there is a coords parameter, it is not quite clear how this is created. It could be added as another column in the CSV file or by adding a line before the url line as follows:

row['coords'] = row['id']   # or whatever format is needed

Note: If you intend using the requests library, the urlencode() is not required. For example:

r = requests.get("https://www.example.com/ImagingService/imagingService", params=row)

You could write each URL to an output CSV file as follows (currently with just one column)

from urllib.parse import urlencode
import csv

with open('parameters.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_input = csv.DictReader(f_input)
    csv_output = csv.writer(f_output)
    csv_output.writerow(['url'])    # write the header
    
    for row in csv_input:
        url = f"https://www.example.com/ImagingService/imagingService?{urlencode(row)}"
        print(url)
        csv_output.writerow([url])

    
Martin Evans
  • 45,791
  • 17
  • 81
  • 97