根据csv fi更改字符串

2024-04-19 22:17:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我得打开几个网站去查一些东西。每个页面的链接之间唯一的区别是我存储在CSV文件中的id。 我想遍历CSV文件并替换每个网站的id。你知道吗

我想用replace语句来做,并更改链接中的xxx。但是它不改变id,并且多次尝试打开与xxx的链接。你知道吗

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"

Tags: 文件csvhttpsimportid网站链接link
3条回答

也可以使用format。你知道吗

for row in reader:
    webbrowser.open('https://website.com/de/tour/{0}/geometrie.html'.format(row))

str.replace返回一个新字符串,因此您必须捕获它:

link = link.replace("xxx", str(row))

尽管最好使用“模板”url,而不是在每次迭代中将link重新分配给带有xxx的url。 具有模板url并使用format创建所需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))

字符串的replace方法返回一个新字符串,并且不会就地修改旧字符串,因此您必须在另一个变量中捕获新字符串或重新使用链接变量

link = link.replace("xxx", str(row))

原因是字符串是不可变的(创建后不能修改)

>>> 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'
>>> 

相关问题 更多 >