【发布时间】:2021-03-11 03:33:09
【问题描述】:
我正在从 API 检索数据,但无法将其保存到文件中。
import requests
import json
response = requests.get(f'url', headers={'CERT': 'cert'})
response = response.json()
当我运行response 或respons.json() 时,我可以看到我想要记录的数据。
我试过了:
str1 = ''.join(map(str, response))
with open('data.txt', mode ='a+') as f:
f.write(f'{str1}')
print("File appended successfully")
f.close()
str1 = ''.join(map(str, response))
with open('data.json', mode ='a+') as f:
f.write(f'{str1}')
print("File appended successfully")
f.close()
with open('data.json', mode ='a+') as results:
result = json.loads(results)
results.write(json.dumps(result, indent=4))
with requests.get(f'url', headers={'CERT': 'cert'}, stream=True) as r:
r.raise_for_status()
with open('data.json', 'wb') as f_out:
for chunk in r.iter_content(chunk_size=8192):
f_out.write(chunk)
with open('data.txt', mode ='a+') as f:
for items in response:
f.write('%s\n' % items)
print("File appended successfully")
f.close()
with open('data.json', mode ='a+') as f:
for items in response:
f.write('%s\n' % items)
print("File appended successfully")
f.close()
还有其他一些没有运气的变体。有人可以指出我正确的方向或让我知道我做错了什么以从response 变量中获取数据以实际填充到文件中吗?
【问题讨论】:
-
这能回答你的问题吗? Saving response from Requests to file
-
感谢您的快速回复。但是这些都没有帮助,代码开始抛出错误列表没有属性“文本”并且列表没有属性“内容”
标签: json python-3.x python-requests python-requests-json