I have to open several websites to check something. The only difference between the links to every page is an id which I have stored in a CSV file. I want to iterate through the CSV file and replace the id for every website.
I want to do it with the replace statement and change the xxx in the link. But it does ́nt change the id and tries to open the link with the xxx several times.
import webbrowser
import csv
link = "https://website.com/de/tour/xxx/geometrie.html"
with open('spielbergList.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print(row)
link.replace("xxx", str(row))
webbrowser.open(link)
print(link)
link = "https://website.com/de/tour/xxx/geometrie.html"
3 Answers 3
str.replace returns a new string, so you will have to catch it:
link = link.replace("xxx", str(row))
Although it will be better to use a "template" url instead of reassigning link to the url with the xxx in every iteration.
An example of having a template url and using format to create the required url:
import webbrowser
import csv
basic_url = "https://website.com/de/tour/{}/geometrie.html"
with open('spielbergList.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print(row)
webbrowser.open(basic_url.format(row))
Comments
the replace method of a string returns a new string and doesn't modify the old one in place so you have to catch the new string in another variable or re-use your link variable
link = link.replace("xxx", str(row))
The reason for this, is that strings are immutable (you can't modify them after creation)
>>> a = 'hello world'
>>> a.replace('hello', 'hi')
'hi world'
>>> a # a is still hello world
'hello world'
>>> a = a.replace('hello', 'hi')
>>> a
'hi world'
>>>
Comments
You can also use format.
for row in reader:
webbrowser.open('https://website.com/de/tour/{0}/geometrie.html'.format(row))