我是python的新手。这就是我想要做的事情。
我在文本文件(mylist.txt)中有计算机名称的列表 mylist.txt: 1234 2356 7879
我需要传递文本文件(mylist.txt)中的每个计算机名称,以命中api并捕获响应并将其存储到文件中。 例: https://abcd.com/MACHINES/1234
我从API获得的响应是XML,每台机器的响应都很大(200行)。
import requests
import xml.etree.ElementTree as ET
url = "https://abcd.com/MACHINES/1234"
user = "xxxxx"
passwd = "xxxxx"
auth_values = (user, passwd)
response = requests.get(url, auth=auth_values)
with open('allmachineresponses.xml', 'wb') as file:
file.write(response.content)
import requests
import xml.etree.ElementTree as ET
with open('mylist.txt') as f_input:
for ids in f_input:
url = "https://abcd.com/MACHINES/{0}".format( ids )
user = "XXXX"
passwd = "XXXX"
auth_values = (user, passwd)
response = requests.get(url, auth=auth_values)
print response.content
能否请您帮助我更正我的代码并存储所有内容 对单个文件的响应
答案 0 :(得分:2)
此行:
url = "https://abcd.com/MACHINES/{0}".format( ids )
应该是这样的:
url = "https://abcd.com/MACHINES/{0}".format(ids.strip())
这将从ids
<=>计算机名称中删除所有换行符或空格。
最好先将整个文件读到内存中,然后将其关闭,然后再循环遍历,这样可以最大程度地减少保持文件引用打开的时间。您可以这样:
with open('mylist.txt') as f_input:
lines = f_input.readlines()
for ids in lines:
url = "https://abcd.com/MACHINES/{0}".format(ids.strip())
user = "XXXX"
passwd = "XXXX"
auth_values = (user, passwd)
response = requests.get(url, auth=auth_values)
print response.content