1 回答
TA贡献1864条经验 获得超6个赞
我建议你使用 pandas 包来写.csv文件,这是一个最常用的数据分析包。
对于您的问题:
import requests
import csv
import json
import pandas
# Make an API call and store response
url = 'https://api-url-goes-here.com'
filename = "test.csv"
headers = {
'accept': 'application/json',
}
r = requests.get(url, headers=headers, auth=('User','PWD'))
print(f"Status code: {r.status_code}")
#Store API response in a variable
response_dict = r.json()
#collect data to build pandas.DataFrame
data = []
for computer in response_dict["advanced_computer_search"]["computers"]:
# filter blank line
if computer["Computer_Name"] or computer["IP_Addresses"]:
data.append({"Computer_Name":computer["Computer_Name"],"IP_Addresses":computer["IP_Addresses"]})
pandas.DataFrame(data=data).to_csv(filename, index=False)
如果你想使用" "分隔值,你可以sep=" "在最后一行设置输出.csv文件。但是,我建议将,其用作分隔符,因为它是通用标准。还可以为 DataFrame.to_csv() 方法设置更多配置,您可以查看官方文档。https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html
正如您在评论中所说,熊猫不是标准的 python 包。您可以简单地打开一个文件并向该文件写入行,其中包含您手动构建的行。例如:
import requests
import csv
import json
# Make an API call and store response
url = 'https://api-url-goes-here.com'
filename = "test.csv"
headers = {
'accept': 'application/json',
}
r = requests.get(url, headers=headers, auth=('User','PWD'))
print(f"Status code: {r.status_code}")
#Store API response in a variable
response_dict = r.json()
r = requests.get(url, headers=headers, auth=('User','PWD'))
print(f"Status code: {r.status_code}")
#Store API response in a variable
response_dict = r.json()
#Open a File for Writing
f = csv.writer(open(filename, "w", encoding='utf8'))
with open(filename, mode='w') as f:
# Write CSV Header
f.write("Computer_Name,"+"IP_Addresses"+"\n")
for computer in response_dict["advanced_computer_search"]["computers"]:
# filter blank line
if computer["Computer_Name"] or computer["IP_Addresses"]:
f.write("\""+computer["Computer_Name"]+"\","+"\""+computer["IP_Addresses"]+"\"\n")
请注意," around value 是通过附加\".来构建的\n,以便在每个循环之后更改新行。
添加回答
举报