我正在从 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
变量中获取数据以实际填充到文件中吗?