首页 > 解决方案 > 如何使用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&currency_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)

标签: pythonrangeoutput

解决方案


不知道为什么 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&currency_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>


推荐阅读