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.

2

1 Answer 1

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

    
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thank you for the solution it's really helpful. How can i write the results in a csv file?
You can use a simple csv.writer(), I have updated the answer to show you how.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.