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])