所以我是 python 的新手,我迫切需要帮助。
我有一个文件,里面有一堆用 em 写的 id(整数值)。它是一个文本文件。
现在我需要将文件中的每个 id 传递到一个 url。
例如“https://example.com/[id]”
会这样进行
A = json.load(urllib.urlopen("https://example.com/(the first id present in the text file)"))
print A
这实际上要做的是,它将读取有关上述 url 中存在的 id 的某些信息并显示它。我希望它以循环格式工作,在这种格式中,它将读取文本文件中的所有 ID,并将其传递给“A”中提到的 url,并连续显示这些值。有没有办法做到这一点?
如果有人能帮助我,我将不胜感激!
最佳答案
可以使用旧式字符串连接
>>> id = "3333333"
>>> url = "https://example.com/%s" % id
>>> print url
https://example.com/3333333
>>>
新样式字符串格式:
>>> url = "https://example.com/{0}".format(id)
>>> print url
https://example.com/3333333
>>>
avasal
提到的文件读取,稍作改动:
f = open('file.txt', 'r')
for line in f.readlines():
id = line.strip('\n')
url = "https://example.com/{0}".format(id)
urlobj = urllib.urlopen(url)
try:
json_data = json.loads(urlobj)
print json_data
except:
print urlobj.readlines()
关于python - 在url中传递一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11131810/