0

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

4

2 回答 2

1

您可以使用json.dump(obj, fp)将对象作为 JSON 格式的流序列化为fp支持.write()操作的文件对象。

import json
with open('data.json', 'w') as fp:
    json.dump(your_json_response, fp)
于 2021-03-11T03:45:35.843 回答
0

首先让我道歉,它一直困扰着我,我发现的代码都没有工作,尤其是没有错误。我跑了print(sys.path),发现我的输出没有去我想要的地方,它进入了一个完全不同的文件夹......所以它一直在工作,只是输出到一个我不知道为什么要输出到的文件夹。感谢大家的帮助。

于 2021-03-11T12:27:07.450 回答