python - 如何使用python将每个循环保存到一个新文件中
问题描述
我试图获得一个 json 响应并将其保存为一个新文件。为此,我试图通过一个范围循环请求,然后我想将每个 json 结果保存为一个新文件
我设法通过循环拉取请求,但我不知道如何将每个输出保存在新文件中。
import requests
import json
for i in range(1, 5):
vino = requests.get('https://www.vivino.com/api/explore/explore?country_code=dk¤cy_code=DKK&grape_filter=varietal&merchant_id=&min_rating=1&order_by=&order=desc&page='+str(i)+'&price_range_max=2500&price_range_min=0&wine_type_ids[]=1&wine_type_ids[]=2')
data = vino.json()
with open('data' + str(i) + '.json', 'w') as outfile:
json.dump(data, outfile)
解决方案
不知道为什么 Milad 建议使用 a write()
— 你的代码基本上没问题,它只需要正确完成缩进。你可以这样做:
import requests
import json
for i in range(1, 5):
vino = requests.get('https://www.vivino.com/api/explore/explore?country_code=dk¤cy_code=DKK&grape_filter=varietal&merchant_id=&min_rating=1&order_by=&order=desc&page='+str(i)+'&price_range_max=2500&price_range_min=0&wine_type_ids[]=1&wine_type_ids[]=2')
data = vino.json()
with open('data' + str(i) + '.json', 'w') as outfile:
json.dump(data, outfile)
请注意最后一行开头的多余空格,它们很重要,并且是人们使用缩进所指的内容。阅读一些 Python 教程可能会有所帮助
使此代码稍微好一点,您可以requests
通过执行以下操作来使用更多界面:
import requests
import json
for page in range(1, 5):
vino = requests.get('https://www.vivino.com/api/explore/explore', params={
'country_code': 'dk',
'currency_code': 'DKK',
'grape_filter': 'varietal',
'min_rating': 1,
'page': page,
'wine_type_ids[]': [1, 2],
})
# raise an exception if this request wasn't successful
vino.raise_for_status()
data = vino.json()
with open('data' + str(page) + '.json', 'w') as outfile:
json.dump(data, outfile)
如果您要自己阅读输出,我会“漂亮地打印”输出,例如:
with open('data' + str(page) + '.json', 'w') as outfile:
json.dump(data, outfile, sort_keys=True,
indent=4, separators=(',', ': '))
最后,如果您使用的是最新版本的 Python3,我还会使用新的“格式字符串”:
with open(f'data{page}.json', 'w') as outfile:
json.dump(data, outfile, sort_keys=True,
indent=4, separators=(',', ': '))
因为它往往会使代码更容易阅读……</p>
推荐阅读
- linux - gdb 无法解析 linux 内核的符号
- java - 在接收器之外的 App Link 中打开应用程序
- c# - c#:如果存在多个 ValidationAttribute,为什么 Validator 会省略 ValidationAttribute 验证?
- c# - 查询其他日历 - Windows Exchange
- javascript - 我可以在 Semantic UI React 的选项数组中为下拉组件指定 Divider 或 Header 吗?
- python - Django NameError:名称“模型”未定义
- maven - pom xml文件的Maven默认评估
- c# - 如何平滑地旋转 uwp 用户控件?
- date - 工艺线选择器。现在在开始日期和结束日期之间或现在大于开始日期和结束日期的位置为空
- tensorflow - 在服务时在 Keras 模型中包含 BEAM 预处理图