如何将Python API调用的输出保存到文件中



编码新手,因此对基本的q.表示歉意

我正在为一个网络安全工具API工作-病毒总量。我正在尝试编写一个程序,该程序将调用API来获取IP地址的报告,然后将该报告保存到文件中。我希望每个API调用都保存在一个不同名称的单独文件中(格式为"report[报告编号]-[DDMMMYYYY].txt">

我试着用open和write命令来实现这一点,但我遇到了错误:TypeError: write() argument must be str, not bytes

我已经成功获得API响应,但我不知道如何将其保存到文件名自动更改的文件中。

有什么想法吗?

我将在下面发布我的代码(我的API密钥经过编辑(。

感谢


url = "https://www.virustotal.com/api/v3/ip_addresses/192.169.69.25"
headers = {
"Accept": "application/json",
"x-apikey": "REDACTED"
}
response = requests.request("GET", url, headers=headers)
with open("testoutput1.txt", "w") as f:
f.write(response)

这已经很晚了,所以您可能已经解决了这个问题,但对于未来的搜索,您可能希望保存json响应(f.write(response.json())(或原始文本(f.write(response.text)(,而不是直接保存response,这正是TypeError: write() argument must be str, not bytes所指示的。

以下是一个示例,其中对使用pathlib进行了细微更改,并根据您的请求格式化文件名:

import json
from datetime import datetime
from pathlib import Path
import requests
url = "https://catfact.ninja/fact"
headers = {
"Accept": "application/json",
}
response = requests.request("GET", url, headers=headers)
# # As a tip, breakpoint can be very helpful when debugging. Try:
# breakpoint()
idx = 1  # Hypothetical index from a for-loop
date = datetime.now().strftime("%d%m%Y")
Path(f"report{idx}-{date}.json").write_text(json.dumps(response.json()))

附带说明一下,使用Python 3.10,您现在可以获得一条更有用的错误消息:TypeError: write() argument must be str, not Response

最新更新